Skip to content

fix(jobs): give job-run Jobs an id label and a bounded TTL (closes #634) - #639

Merged
fatih-acar merged 2 commits into
developfrom
ai-bug-pipeline-634-job-leak-ttl-3dea34a44bbf864e
Dec 1, 2026
Merged

fatih-acar merged 2 commits into
developfrom
ai-bug-pipeline-634-job-leak-ttl-3dea34a44bbf864e

Conversation

@opsmill-bug-pipeline

@opsmill-bug-pipeline opsmill-bug-pipeline Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Analyst's findings (summary)

Root cause: _build_job_manifest (used by the runJob mutation's flow path, backend/styrmin_backend/agent/tasks/orchestration.py:514-576) creates a Kubernetes Job with no ttlSecondsAfterFinished and no Styrmin id label. Nothing elsewhere in the codebase ever deletes a job-run-* Job (the only Job-delete path, _delete_earlier_job in backend/styrmin_backend/agent/service/kubernetes/primitives.py:733-798, is scoped to a different, fixed-name Job used by execute_commands and never matches job-run-* Jobs). So every runJob call permanently accumulates one more Job and pod in the deployment's namespace, and the Job also can't be found by a Styrmin record id per ADR-073.
Affected files: backend/styrmin_backend/agent/tasks/orchestration.py (_build_job_manifest, lines 514-576), backend/styrmin_backend/agent/service/kubernetes/primitives.py (run_kubernetes_job, lines 91-125; _delete_earlier_job, lines 733-798), backend/styrmin_backend/api/schema/mutation.py (run_job mutation, lines 1388-1406).

Replication test

Test file: backend/tests/unit/agent/tasks/test_run_job_flows.py
Test name: test_build_job_manifest_is_findable_by_id_and_bounded_in_lifetime
What it tests: calls the production _build_job_manifest function directly (the same manifest builder run_job_command uses to create the Job via run_kubernetes_job) and asserts the resulting manifest carries (a) a metadata.labels entry whose value is the task's id, so the Job is selectable by id per ADR-073, and (b) a positive integer spec.ttlSecondsAfterFinished, so Kubernetes garbage-collects the Job instead of it accumulating forever.

Local run (evidence)

backend/tests/unit/agent/tasks/test_run_job_flows.py::test_build_job_manifest_is_findable_by_id_and_bounded_in_lifetime FAILED [100%]

======================================================= FAILURES =======================================================
__________________________ test_build_job_manifest_is_findable_by_id_and_bounded_in_lifetime ___________________________

    def test_build_job_manifest_is_findable_by_id_and_bounded_in_lifetime() -> None:
        task_id = uuid4()

        manifest = orchestration._build_job_manifest(**_job(task_id))

        labels = manifest["metadata"].get("labels") or {}
>       assert str(task_id) in labels.values()
E       AssertionError: assert '4891f699-b22d-41f6-90f5-af169d037273' in dict_values([])
E        +  where '4891f699-b22d-41f6-90f5-af169d037273' = str(UUID('4891f699-b22d-41f6-90f5-af169d037273'))
E        +  and   dict_values([]) = <built-in method values of dict object at 0x7dec510a5980>()
E        +    where <built-in method values of dict object at 0x7dec510a5980> = {}.values

backend/tests/unit/agent/tasks/test_run_job_flows.py:364: AssertionError
=============================================== short test summary info ================================================
FAILED backend/tests/unit/agent/tasks/test_run_job_flows.py::test_build_job_manifest_is_findable_by_id_and_bounded_in_lifetime
1 failed, 8 passed in 4.97s

The other 8 pre-existing tests in the file still pass unchanged, confirming the new test is the only one exercising the missing behavior.

Expected CI signal: the Unit Tests check should FAIL on this PR, for this reason: _build_job_manifest currently emits a manifest with no metadata.labels key at all and no spec.ttlSecondsAfterFinished, which is exactly the root cause of the Job/pod leak described in #634.

Test expectations

The test asserts the mechanism, not an exact TTL value (the issue states the retention duration is "Not decided yet"):

  • manifest["metadata"]["labels"] exists and contains the task's id as one of its values (an id label the Job can be found by, per ADR-073), rather than relying only on the generateName: job-run-<task_id>- prefix.
  • manifest["spec"]["ttlSecondsAfterFinished"] is present and is a positive integer, so Kubernetes removes the Job (and its pod) after it finishes instead of it accumulating indefinitely.

It deliberately does not assert a specific TTL number, a specific label key, or touch run_kubernetes_job / _delete_earlier_job — per the analyst's note, the fix belongs in _build_job_manifest alone and the exact TTL is a separate product decision.

AGENT_TEST_COMPLETE

Generated by Bug test-writer agent · claude · agent · ~58 AIC · ⌖ ~2 AIC · ⊞ 5.5K · ◷

Add this agentic workflow to your repo

To install this agentic workflow, run

gh aw add opsmill/opsmill-cicd-workflows/workflows/bug-agent-test.md@main

<!-- This is an auto-generated description by cubic. -->
<a href="(cubic.dev/redacted) target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="(www.cubic.dev/redacted)&lt;source media="(prefers-color-scheme: light)" srcset="(www.cubic.dev/redacted)&lt;img alt="View guided diff" src="(www.cubic.dev/redacted)&lt;/picture&gt;&lt;/a> <a href="(www.cubic.dev/redacted) target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="(www.cubic.dev/redacted)&lt;source media="(prefers-color-scheme: light)" srcset="(www.cubic.dev/redacted)&lt;img alt="Turn on auto-fix" src="(www.cubic.dev/redacted)&lt;/picture&gt;&lt;/a>

<!-- End of auto-generated description by cubic. -->


Fix strategy

Followed the analyst's root-cause and fix strategy as-is, scoped entirely to _build_job_manifest in backend/styrmin_backend/agent/tasks/orchestration.py:

  • Added a metadata.labels block to the Job manifest: app.kubernetes.io/managed-by: styrmin and styrmin.io/task-id: <task_id> (new TASK_ID_LABEL constant), so the Job is selectable by a Styrmin record id per ADR-073, not only by its generateName prefix.
  • Added spec.ttlSecondsAfterFinished (new _JOB_FINISHED_TTL_SECONDS = 3600) so Kubernetes garbage-collects the Job (and its pod) a bounded time after it reaches Complete/Failed, instead of it accumulating forever.
  • Per the analyst's notes, the exact TTL duration is an open product decision (the issue says "Not decided yet"); 3600 is a placeholder — flagged with a comment at the definition site — not a final product decision. Happy to adjust to whatever value the team settles on; it's a single constant.
  • Did not touch _delete_earlier_job / ACTION_JOB_LABEL or add an explicit delete call, per the analyst's explicit "Do NOT" guidance — ttlSecondsAfterFinished is the Kubernetes-native mechanism and avoids a race with that function's unrelated same-name-replacement use case (fix(actions): execute_commands can run only once per deployment namespace (Job never cleaned up) #374).
  • Updated the pre-existing _expected_manifest helper in test_run_job_flows.py (used by test_run_job_command_runs_the_job_as_the_command_step, which asserts the full manifest by exact equality) to include the new labels and ttlSecondsAfterFinished keys, since production output legitimately changed. The new replication test (test_build_job_manifest_is_findable_by_id_and_bounded_in_lifetime) itself was not modified.
  • Added a towncrier changelog fragment (changelog/634.fixed.md).

Local run (evidence)

Replication test, now passing:

backend/tests/unit/agent/tasks/test_run_job_flows.py::test_build_job_manifest_is_findable_by_id_and_bounded_in_lifetime PASSED

Full test file (9/9 passed):

$ uv run pytest backend/tests/unit/agent/tasks/test_run_job_flows.py -v
======================================================== 9 passed in 9.21s ========================================================

Affected unit suite (backend/tests/unit/agent/, 762/762 passed):

$ uv run pytest backend/tests/unit/agent/ -q
762 passed, 33 warnings in 11.07s

Full backend unit suite: 5012 passed, 6 skipped, 9 failed, 237 errors — all pre-existing and environmental (Docker daemon unavailable for testcontainers-backed Postgres migration tests in this sandbox); none touch orchestration.py, run_job, or _build_job_manifest (confirmed against .pytest_cache/v/cache/lastfailed).

uv run invoke format lint (backend ruff/ty, frontend eslint/prettier, GraphQL schema validation, codegen-freshness check): all green. No GraphQL schema or query files were touched, so no schema.graphql / SDK regeneration was needed.

AGENT_FIX_COMPLETE

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • telemetry.invalid

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "telemetry.invalid"

See Network Configuration for more information.

Generated by Bug fixer agent · claude · agent · ~185 AIC · ⌖ ~2 AIC · ⊞ 5.3K · ◷

Add this agentic workflow to your repo

To install this agentic workflow, run

gh aw add opsmill/opsmill-cicd-workflows/workflows/bug-agent-fix.md@main

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Deploying styrmin with  Cloudflare Pages  Cloudflare Pages

Latest commit: 45d05fe
Status: ✅  Deploy successful!
Preview URL: https://fa1a21b4.styrmin.pages.dev
Branch Preview URL: https://ai-bug-pipeline-634-job-leak.styrmin.pages.dev

View logs

@polmichel polmichel self-assigned this Nov 30, 2026
@polmichel polmichel added the state/ai-pipeline-ready Approval gate: this issue/PR may be handled by the bug-fixing pipeline label Nov 30, 2026
@opsmill-bug-pipeline

Copy link
Copy Markdown
Contributor Author

AGENT_REVIEW_VERDICT: TEST_APPROVED

Verdict: Approved

Realism

_job()'s fixture (task_id, runtime_class="kata", env, namespace="styrmin-app", commands, image="busybox:1.36") mirrors exactly what run_job_command passes to _build_job_manifest at the real call site (orchestration.py, run_job_command → _build_job_manifest(task_id=..., runtime_class=..., env=..., namespace=..., commands=..., image=...)). No invented shape.

Correctness

The test calls the production _build_job_manifest directly and asserts:

  • manifest["metadata"]["labels"] contains str(task_id) as a value — an id label the Job can be found by, per ADR-073.
  • manifest["spec"]["ttlSecondsAfterFinished"] is a positive int.

I confirmed against the current _build_job_manifest body (orchestration.py:513-576) that metadata has no labels key at all and spec has no ttlSecondsAfterFinished key — so this test cannot pass without the affected code path actually changing. It can't pass by accident.

Quality

Pure unit test, no I/O, no mocks needed, colocated with the 8 existing tests for this module and reusing the existing _job helper. Deterministic.

Alignment

Matches the analyst's root cause precisely: fix scoped to _build_job_manifest only, no assertion on a specific TTL value or label key (correctly left as a product decision per the issue), and doesn't touch run_kubernetes_job / _delete_earlier_job as the analyst specified.

CI signal

Unit Tests check concluded failure — expected and correct for a test-only PR proving the bug. All other checks (Integration, E2E across all shards, Frontend, Pre-Commit) are green, confirming the new test is isolated and doesn't destabilize anything else.

AGENT_REVIEW_ITERATION: test-1

Generated by Bug reviewer agent · claude · agent · ~36 AIC · ⌖ ~1 AIC · ⊞ 5.2K · ◷

Add this agentic workflow to your repo

To install this agentic workflow, run

gh aw add opsmill/opsmill-cicd-workflows/workflows/bug-agent-review.md@main

@polmichel

Copy link
Copy Markdown
Collaborator

/bug-fix

@opsmill-bug-pipeline opsmill-bug-pipeline Bot changed the title test: failing test for #634 — runJob Jobs/pods leak, no id label or TTL fix(jobs): give job-run Jobs an id label and a bounded TTL (closes #634) Dec 1, 2026
_build_job_manifest built the runJob mutation's Job with no
ttlSecondsAfterFinished and no Styrmin id label, so Kubernetes never
garbage-collected it and nothing else in the codebase deleted it either.
Every runJob call therefore permanently left one more Job and its pod in
the deployment's namespace, and the Job could not be selected by a
Styrmin record id label per ADR-073.

Add a styrmin.io/task-id label (plus app.kubernetes.io/managed-by) and
a ttlSecondsAfterFinished to the manifest so the Job is findable by id
and Kubernetes removes it a bounded time after it finishes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@opsmill-bug-pipeline

Copy link
Copy Markdown
Contributor Author

Commit pushed: 45d05fe

Generated by Bug fixer agent · claude · agent · ~185 AIC · ⌖ ~2 AIC · ⊞ 5.3K

@opsmill-bug-pipeline

Copy link
Copy Markdown
Contributor Author

AGENT_REVIEW_VERDICT: FIX_APPROVED

Verdict: Approved

Correctness

The fix is scoped exactly to _build_job_manifest in backend/styrmin_backend/agent/tasks/orchestration.py, matching the analyst's root cause and fix strategy:

  • Adds metadata.labels with styrmin.io/task-id: <task_id> (new TASK_ID_LABEL constant) and app.kubernetes.io/managed-by: styrmin — the Job is now selectable by a Styrmin record id per ADR-073, not only by its generateName prefix.
  • Adds spec.ttlSecondsAfterFinished = 3600 (new _JOB_FINISHED_TTL_SECONDS), so Kubernetes garbage-collects the Job (and its pod) a bounded time after Complete/Failed, closing the leak in fix(jobs): the Jobs that runJob creates are never deleted, so each run leaves a Job and its pod in the deployment namespace #634.
  • Confirmed _delete_earlier_job/ACTION_JOB_LABEL in primitives.py is untouched and scoped to a different (fixed-name, action-job) use case, so there's no interaction/race with that path, per the analyst's explicit "Do NOT" guidance.
  • Confirmed run_kubernetes_job doesn't need a lookup-by-id path today (it reads back the created Job by the name Kubernetes assigns via generateName), so the label alone correctly satisfies the ADR-073 "findable by id" requirement without unrelated code changes.
  • Replication test test_build_job_manifest_is_findable_by_id_and_bounded_in_lifetime now passes and was not modified by the fixer (verified via git diff between the test-writer's commit and the fix commit — only the pre-existing _expected_manifest helper changed, which legitimately needed the new keys for its exact-equality assertion). Test integrity holds.
  • TTL value (3600s) is explicitly flagged as a placeholder pending product decision, consistent with the issue's "Not decided yet" note — appropriately not over-committing to a number the analyst said was undecided.

Code quality

  • TASK_ID_LABEL = "styrmin.io/task-id" and app.kubernetes.io/managed-by: styrmin both match established label conventions elsewhere in the codebase (DEPLOYMENT_ID_LABEL, BSL_ID_LABEL, ACTION_JOB_LABEL all follow the same styrmin.io/<kind>-id pattern; app.kubernetes.io/managed-by: styrmin is used identically in actions/primitives.py, service_aliases.py, and the utility resource builder).
  • No unrelated refactor; the incidental trailing-comma fix in the existing template dict is harmless formatting noise from the same edit.
  • No perf/security regressions.

Documentation alignment

No ADR/guide describes per-field TTL/label specifics for this Job, and this is an internal manifest-construction detail, not a user-visible CLI/SDK/GraphQL/driver-format change, so no doc update is required here. A towncrier fragment (changelog/634.fixed.md) was added as required.

Test integrity

Confirmed unchanged — see above.

CI signal

The authoritative Unit Tests check (where the replication test lives) is green (conclusion: success), confirming the fix makes the previously-failing test pass. Other checks (Integration, Frontend, SDK, Pre-Commit, CLI) are also green; several E2E shards are still in progress but none are required to evaluate this unit-level fix.

AGENT_REVIEW_ITERATION: fix-1

Generated by Bug reviewer agent · claude · agent · ~49 AIC · ⌖ ~1 AIC · ⊞ 5.2K · ◷

Add this agentic workflow to your repo

To install this agentic workflow, run

gh aw add opsmill/opsmill-cicd-workflows/workflows/bug-agent-review.md@main

@polmichel
polmichel marked this pull request as ready for review December 1, 2026 13:51
@fatih-acar
fatih-acar merged commit 057f2f9 into develop Dec 1, 2026
26 checks passed
@fatih-acar
fatih-acar deleted the ai-bug-pipeline-634-job-leak-ttl-3dea34a44bbf864e branch December 1, 2026 13:56
polmichel added a commit that referenced this pull request Dec 4, 2026
…or a test run

Reinstalled from opsmill/opsmill-cicd-workflows@fix/bug-pipeline-marker-reads
(opsmill/opsmill-cicd-workflows#67) to run the reviewer once on #639. Repoint to
@main after #66 and #67 merge.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/ai-pipeline-ready Approval gate: this issue/PR may be handled by the bug-fixing pipeline

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants