Skip to content

fix: serve the backend's logs in the view FULL - #419

Merged
uniqueg merged 6 commits into
devfrom
fix/full-view-logs
Nov 4, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/full-view-logs

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Closes #413

Summary

docs/api.md promised backend logs in the view FULL, but proTES only polled in the view BASIC, which has none. Now a finished task is got once more in the view FULL.

  • proTES stores stdout, stderr and system_logs, at most post_task.max_log_size per task (default 1 MiB, at most 8 MiB, 0 turns it off): short logs are kept, the longer ones share the rest and keep their end.
  • A failed fetch doesn't lose the final state or outputs: it is logged, and the task of the last poll is used.
  • Final state and logs are stored in one update, as clients may read the logs once, right after the state.
  • Responses of the view FULL are limited to 64 MiB and custom.tes.timeout as a whole, also for configured backends.
  • A poll delivered again skips the fetch, so a response that cost a worker its memory can't keep a task from finishing.
  • If MongoDB refuses a document (too large, or values it can't encode), the task is stored without log texts, then also without executor logs and outputs, and finally with only its state; tracking ends with an error in the log instead of retrying forever.
  • Docs: docs/api.md, docs/configuration.md, docs/upgrading.md.
  • Smoke test: the fake serves logs only in the view FULL; check.sh asserts them for FULL and their absence for BASIC.

Verification

  • python -m pytest with real Helm: all passed. pre-commit run --from-ref origin/dev --to-ref HEAD: passed.
  • The review of the fallback ran against a real MongoDB 7.0: client-side DocumentTooLarge and server-side code 10334 both end in a stored task. Test (MongoDB 7.0) in CI runs test_too_many_logs.
  • Compose smoke test and docs build: run in CI only.
  • Not run: a real TESK, TESP or Funnel; a worker killed for lack of memory, so the redelivery is tested only by setting its flag.

Declined review findings

  • Broad except Exception in _full_task, logging the type name only: messages of py-tes errors contain the whole task; no database call runs inside it.
  • No retry of the FULL fetch: best effort, documented in docs/api.md.
  • 8 MiB cap not validated against raised request limits: the fallback for documents that are refused covers it.
  • Log texts aren't scrubbed for credentials: documented, and only the owner of a task can read them.
  • Redirect bodies aren't limited for configured backends, as requests reads them whole: these backends are chosen by the admin; the module's docstring has the same gap for FOCA's client.
  • Cancels during the FULL fetch may meet a refusal of the backend: answered by the re-read in Small findings of the 0.5.0 review #418.
  • A 64 MiB response can take a worker process up to about 420 MiB, measured by the reviewer, so that two at once can exceed the worker's 512 MiB: kept at 64 MiB, like for discovered backends, as the redelivery breaks the loop; documented in docs/configuration.md.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Retrieve and safely persist completed TES backend logs in the FULL view while protecting task completion from oversized responses and storage failures.

New Features:

  • Serve completed task logs from TES backends through the FULL view, including executor stdout/stderr and system logs.
  • Add configurable per-task log storage limits with truncation and an option to disable backend log retrieval.

Bug Fixes:

  • Preserve final task state and available outputs when fetching or storing backend logs fails.
  • Prevent oversized or unencodable MongoDB documents from causing endless tracking retries by progressively storing reduced task data.
  • Avoid repeating expensive FULL log fetches for redelivered polls so completed tasks can still finish.

Enhancements:

  • Apply response size and whole-request timeout limits to FULL task requests for all backend types.
  • Store final state and logs atomically so clients can retrieve logs immediately after observing completion.

Documentation:

  • Document FULL-view backend logs, log size configuration, failure behavior, and upgrade considerations.

Tests:

  • Add backend response-limit and timeout coverage, task-tracking tests for log retrieval and storage fallbacks, and smoke coverage verifying logs appear only in FULL.

uniqueg and others added 4 commits November 4, 2026 06:49
Get a finished task once more in the view `FULL` from its backend, and
store its stdout, stderr and system logs, at most
`post_task.max_log_size` per task, keeping the end of longer ones. A
failure of this request keeps the final state and the rest of the logs.

Closes #413

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Extract the share of logs into a function with its own tests, and state
in the docs that a failure of the one request leaves a task without logs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Findings of the review of the view FULL:

- Limit responses of the view FULL of configured backends as well, as
  logs of any size could exhaust the memory of a worker, again with
  each delivery of the poll.
- Store a task with less if MongoDB refuses it, instead of retrying
  forever (many short logs aren't covered by the size limit).
- Get the logs before storing the final state, for clients that read
  them once, right after it.
- Keep no log texts at all with max_log_size 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Findings of the second review round:

- Store the final state and the logs in one update, as clients may read
  them once, and only the state alone if that fails.
- Skip the view FULL when a poll is delivered again, so that a response
  that cost a worker can't keep a task from finishing.
- Limit the time of reading the view FULL as a whole.
- Store with less also if values can't be encoded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.5.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Completed tasks now make a bounded, best-effort FULL-view fetch for backend logs and atomically persist those logs with the final state, with response, memory, redelivery, and MongoDB-size safeguards plus documentation and test coverage.

Sequence diagram for fetching and storing completed task logs

sequenceDiagram
    participant Worker as CeleryWorker
    participant TES as TESBackend
    participant DB as MongoDB

    Worker->>TES: get_task(remote_task_id, view=BASIC)
    TES-->>Worker: Finished task state
    opt first delivery and max_log_size > 0
        Worker->>TES: get_task(remote_task_id, view=FULL)
        TES-->>Worker: State, stdout, stderr, system_logs, outputs
    end
    Worker->>Worker: _limit_logs(logs, max_log_size)
    Worker->>DB: _store_within_limit(state, logs, outputs)
    DB-->>Worker: Final state and logs stored atomically
Loading

Flow diagram for resilient final task storage

flowchart TD
    A[Finished task received] --> B{Poll redelivered?}
    B -->|No| C[Fetch FULL view]
    B -->|Yes| D[Use last poll response]
    C --> E{FULL fetch succeeds with same state?}
    E -->|No| D
    E -->|Yes| F[Limit log texts]
    D --> F
    F --> G{MongoDB accepts state and logs?}
    G -->|Yes| H[Tracking ends]
    G -->|No: document too large or invalid| I[Drop log texts]
    I --> J{MongoDB accepts reduced task?}
    J -->|Yes| H
    J -->|No| K[Drop executor logs and outputs]
    K --> L{MongoDB accepts state?}
    L -->|Yes| H
    L -->|No| M[Store state only and log error]
Loading

File-Level Changes

Change Details Files
Fetch and persist completed-task backend logs through the FULL view while preserving atomic final-state updates.
  • Perform a one-time FULL fetch after a task reaches a finished state.
  • Fall back to the BASIC poll result when the FULL fetch fails or reports a different state.
  • Store final state, executor logs, system logs, and outputs in one database update.
pro_tes/tasks/track_task_progress.py
docs/api.md
docs/upgrading.md
tests/tasks/test_track_task_progress.py
tests/smoke/fake_tes.py
tests/smoke/check.sh
Bound log and response sizes to protect Celery workers and MongoDB while retaining useful task completion data.
  • Add configurable max_log_size validation and default it to 1 MiB, with an 8 MiB maximum and zero disabling log retrieval.
  • Truncate logs by UTF-8 byte size while preserving their ends and distribute remaining capacity across longer log fields.
  • Apply a 64 MiB response cap and whole-response timeout to FULL requests, including configured backends.
  • Retry MongoDB persistence with progressively reduced log content, then retain only final state if storage remains impossible.
pro_tes/config_models.py
pro_tes/config.yaml
pro_tes/ga4gh/tes/backends.py
pro_tes/tasks/track_task_progress.py
docs/configuration.md
tests/ga4gh/tes/test_backends.py
tests/tasks/test_track_task_progress.py
Make task tracking resilient to failed finalization and broker redelivery.
  • Persist the final state when log storage fails and allow Celery to retry unrelated database errors.
  • Skip the potentially expensive FULL fetch for redelivered polls so tasks can finish after resource pressure.
  • Add coverage for fetch failures, state mismatches, redelivery, truncation, storage fallbacks, response limits, and MongoDB-specific size errors.
pro_tes/tasks/track_task_progress.py
tests/tasks/test_track_task_progress.py
Document the new FULL-view behavior, configuration limits, operational impact, and upgrade semantics.
  • Explain when backend logs become available, how they are truncated or omitted, and the associated response and memory limits.
  • Document the new max_log_size setting and effects on stored tasks and FULL-view pages.
docs/api.md
docs/configuration.md
docs/upgrading.md

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@read-the-docs-community

read-the-docs-community Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 proTES | 🛠️ Build #35634170 | 📁 Comparing 57738f4 against latest (ea0ec59)

  🔍 Preview build  

4 files changed
± api/index.html
± configuration/index.html
± reference/index.html
± upgrading/index.html

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (ea0ec59) to head (57738f4).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #419    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           24        24            
  Lines         2542      2642   +100     
==========================================
+ Hits          2542      2642   +100     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 4, 2026 05:59

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 7 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="pro_tes/ga4gh/tes/backends.py" line_range="1062" />
<code_context>
+    content = bytearray()
+    deadline = time.monotonic() + timeout
+    with response:
+        for chunk in response.iter_content(chunk_size=RESPONSE_CHUNK_SIZE):
+            content += chunk
+            if len(content) > MAX_RESPONSE_SIZE:
</code_context>
<issue_to_address>
**Body reads exceed timeout**

When a backend slowly streams a response without triggering the per-read timeout, `read_limited` checks the deadline only after `iter_content` yields a chunk, so a blocking read can keep a worker occupied beyond `custom.tes.timeout` before the timeout is raised.

Limit each blocking body read to the time remaining before the whole-request deadline.

Also at `pro_tes/ga4gh/tes/backends.py:1069-1071`.
</issue_to_address>

### Comment 2
<location path="pro_tes/ga4gh/tes/backends.py" line_range="925" />
<code_context>
+            if limited:
+                return read_limited(
+                    requests.request(
+                        method, url, timeout=timeout, stream=True, **kwargs
+                    ),
+                    timeout=timeout[1],
</code_context>
<issue_to_address>
**Header reads exceed timeout**

When a backend slowly sends response headers while avoiding the per-read timeout, `requests.request` waits for the headers before `read_limited` starts its deadline, so the request can keep a worker blocked beyond `custom.tes.timeout` and delay task completion.

Apply the whole-request deadline while waiting for response headers as well as while reading the body.

Also at `pro_tes/ga4gh/tes/backends.py:1060`.
</issue_to_address>

### Comment 3
<location path="pro_tes/tasks/track_task_progress.py" line_range="328-330" />
<code_context>
+                    mode="json", exclude_none=True, include={"state", "logs"}
+                ),
+            )
+        except (InvalidDocument, UnicodeEncodeError, OperationFailure) as exc:
+            if isinstance(exc, OperationFailure) and exc.code not in TOO_LARGE_CODES:
+                raise
+            logger.error(
+                "[%s] Logs of the finished task can't be stored: %s",
</code_context>
<issue_to_address>
**Oversized documents keep retrying**

When mongoDB's client-side BSON encoding rejects the final document as too large, `DocumentTooLarge` is not included in the caught exception types, so `_store_within_limit` propagates the client-side size refusal instead of dropping log data and retrying the write. `_poll` then retries the final task indefinitely rather than finishing tracking.

Catch `DocumentTooLarge` alongside the other document-size failures so the fallback reductions run.
</issue_to_address>

### Comment 4
<location path="pro_tes/tasks/track_task_progress.py" line_range="229" />
<code_context>
+            worker_id,
+        )
+        return basic
+    return full
+
+
</code_context>
<issue_to_address>
**BASIC outputs are lost**

When the BASIC poll contains outputs and the FULL response has missing, null, or empty logs, `_full_task` accepts the FULL response, so `_store_final` either fails or stores no outputs from it; the outputs from the BASIC poll are lost.

Treat a FULL response without logs as unavailable and use the BASIC response as the fallback.

Also at `pro_tes/tasks/track_task_progress.py:214`.
</issue_to_address>

### Comment 5
<location path="pro_tes/tasks/track_task_progress.py" line_range="523-530" />
<code_context>
+        return
+    # not if the message is delivered again: getting the logs may have cost its
+    # worker (e.g., out of memory), which must not keep the task from finishing
+    if not redelivered:
+        response = _full_task(
+            cli=cli,
+            worker_id=worker_id,
+            remote_task_id=kwargs["remote_task_id"],
+            basic=response,
+        )
+    try:
+        _store_final(db_client=db_client, worker_id=worker_id, response=response)
+    except Exception:
</code_context>
<issue_to_address>
**Redelivery erases stored logs**

When the worker commits the final state and FULL logs, then dies before Celery acknowledges its late-ack message, the redelivered poll skips `_full_task` but still passes the BASIC response to `_store_final`, which replaces the stored executor and system logs with the BASIC response’s omitted log text. Users permanently lose logs that were already committed.

On redelivery, avoid replacing already-stored final logs with BASIC-view logs; preserve the committed final data or make the final write conditional on the task not already being finalized.
</issue_to_address>

### Comment 6
<location path="tests/tasks/test_track_task_progress.py" line_range="348" />
<code_context>
+    error: Exception,
+) -> None:
+    """A failure to get the logs doesn't lose the final state and the outputs."""
+    client_class.full_error = error
+    run()
+    document = tasks.find_one({"worker_id": ARGS["worker_id"]})
</code_context>
<issue_to_address>
**Fetch failure path goes untested**

When the `FULL` fetch is removed or bypassed, `test_full_logs_unavailable` only checks the final state, outputs, and scheduling; it never asserts that the `FULL` request was attempted. If `_poll` stops fetching `FULL`, the configured error is unused and the test passes.

Assert that `client_class.views` includes `FULL` in this test.
</issue_to_address>

### Comment 7
<location path="tests/tasks/test_track_task_progress.py" line_range="375" />
<code_context>
+        assert document is not None
+        assert document["task"]["state"] == "QUEUED"
+        assert kwargs["state"] == "COMPLETE"
+        assert kwargs["logs"]
+        return upsert(self, **kwargs)
+
</code_context>
<issue_to_address>
**Atomic write can omit backend logs**

When the `FULL` response's log texts are omitted while existing task-log entries remain, `test_full_logs_with_final_state` accepts any truthy `kwargs["logs"]`; the existing task-log entry is truthy even when it contains no backend log text. The final state can therefore be written with stale logs and the test still passes.

Configure nonempty FULL log texts and assert that those texts are included in the same upsert as the final state.
</issue_to_address>

Linked issues

#413 fix: serve the backend's logs in the view FULL · 7 of 7 met

# Requirement Status Notes
1 When a task is final, get it once with view FULL ✅ Met The final-poll path makes one FULL request unless the poll was redelivered or log retrieval is disabled.
2 If that request fails, keep what the last poll got so the final state is not lost ✅ Met A failed fetch or a FULL response reporting another state falls back to the last poll's task before storing the final result.
3 Store stdout, stderr and system_logs ✅ Met Final-task storage copies executor logs and system logs into the stored task.
4 Limit the size of those logs per task ✅ Met The configurable per-task limit covers stdout, stderr and system logs; longer texts are truncated, and storage has further fallbacks if MongoDB refuses the document.
5 Add tests ✅ Met Tests cover FULL retrieval, fetch failures, log limits and storage fallbacks.
6 Add a smoke case ✅ Met The smoke test checks that FULL includes backend logs and BASIC omits them.
7 Update the docs ✅ Met API, configuration and upgrading docs describe the FULL-view logs and their limits.

Sourcery assessment

Needs a human reviewer. 7 findings to address first, and with the default enabled, proTES fetches and persistently stores backend logs that task owners can read through the FULL view; logs may contain secrets, and the change makes that collection the default without a failure signal. Reverting stops future collection but does not remove logs already stored, and the per-task cap does not bound exposure across tasks.

Blocking findings: pro_tes/ga4gh/tes/backends.py:1062, pro_tes/ga4gh/tes/backends.py:925, pro_tes/tasks/track_task_progress.py:330, pro_tes/tasks/track_task_progress.py:229, pro_tes/tasks/track_task_progress.py:530, and 2 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Comment thread pro_tes/tasks/track_task_progress.py Resolved
Comment thread pro_tes/tasks/track_task_progress.py Resolved
Comment thread pro_tes/tasks/track_task_progress.py Resolved
Comment thread tests/tasks/test_track_task_progress.py Resolved
Comment thread tests/tasks/test_track_task_progress.py Resolved
uniqueg and others added 2 commits November 4, 2026 07:09
Findings of the automated review:

- A poll delivered again after a task was stored no longer replaces its
  logs with those of the view BASIC.
- A view FULL without logs no longer loses the outputs of the last poll.
- Read limited responses with single reads, as whole chunks can take any
  time, which the time limit didn't cover.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 427021f into dev Nov 4, 2026
32 checks passed
@uniqueg
uniqueg deleted the fix/full-view-logs branch November 4, 2026 06:25
uniqueg added a commit that referenced this pull request Nov 4, 2026
Brings in the review fixes #410, #412, #417, #419, #420, #421.

The only conflict is in the module docstring of
`pro_tes/ga4gh/tes/backends.py`: keeps this branch's removal of the
FOCA 0.19 caveat about redirects, and the sentence of #419 about tasks
in the view `FULL`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

fix: serve the backend's logs in the view FULL

1 participant