Skip to content

Speak the upstream runner's protocol: job outputs, per-job logs, gh host, annotations - #34

Merged
waynesun09 merged 7 commits into
mainfrom
emu-03-runner-protocol
Nov 19, 2026
Merged

waynesun09 merged 7 commits into
mainfrom
emu-03-runner-protocol

Conversation

@waynesun09

@waynesun09 waynesun09 commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Part of #39

Five fixes that make the upstream actions/runner behave as it does against GitHub. On GitHub this runner gets job outputs, per-job logs, a working gh and ::notice:: lines. On the emulator it got none of these. The emulator's Python runner gets one small fix as well.

What it fixes

Area GitHub Emulator before
Job outputs needs.<job>.outputs.<name> carries the value the job set Always empty: no jobOutputs template in the job message, plan version 1 (the worker only raises JobCompleted from version 8), and no plan events resource
Logs and timeline Each job's console lines, step logs and step states land on that job The job was looked up by plan, which is the whole run, so with two jobs running one job's lines went to the other. Log creation had no path, so every step-log upload threw. Timeline updates were a bare array, which the worker resent forever
gh in a step gh talks to the server the job came from gh ignores GITHUB_API_URL, so it went to api.github.com with the job token: "Bad credentials"
::notice:: Rendered as ##[notice] Left raw, because the job message did not set DistributedTask.EnhancedAnnotations
Python runner bash (actions/runner) the bash on PATH Always /bin/bash, which on macOS is bash 3.2 and rejects bash 4 syntax

Changes

  • src/app/api/actions_distributed_task.py:
    • sends jobOutputs, declares plan version 8, and serves the plan events resource. JobCompleted stores the outputs and completes the job. The route takes it only with a valid job token for that job (validate_job_token: signature and expiry) and only while the job is in progress;
    • finds the job from the job token; answers log creation with a path and its own id; keeps step logs beside the job log; answers timeline updates as {count, value};
    • sets GH_HOST for every step and mirrors the step's chosen token into GH_ENTERPRISE_TOKEN. A step that names no token gets none, and a workflow's own value wins;
    • sets DistributedTask.EnhancedAnnotations.
  • src/runners/emulator/runner.py: resolves bash from the step's PATH, falling back to /bin/bash.
  • A bug note per fix under docs/bugs/fixed/, and its PLAN.md line.

Tests

  • New: tests/actions/test_runner_job_outputs.py (10), tests/actions/test_runner_job_logs.py, tests/actions/test_runner_gh_host.py (6). They check routes, fields and variables the old code did not have. The two event tests (a repeated JobCompleted, a token whose signature does not match) were each run against the code without their check and fail there.
  • Updated: tests/actions/test_execution.py checks GH_HOST and EnhancedAnnotations in the job message.
  • The bash lookup has no new test. The existing step tests run it on a host where the PATH bash is /bin/bash.
  • Locally: these four files pass.
  • Full suite: runs in this pull request's CI (ci.yml).

Effect on existing behaviour

  • Only the upstream-runner job server changes, plus one line of the Python runner.
  • A workflow that never reads job outputs, gh or ::notice:: sees no difference, except that its logs now land on the right job.
  • The runner now calls JobCompleted to finish a job, because plan version 8 stops the listener from finishing the job request.

@waynesun09
waynesun09 requested a review from jctanner November 18, 2026 22:41
@qodo-code-review

qodo-code-review Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Align runner protocols for outputs, logs, gh, and annotations

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Deliver upstream runner job outputs to dependent jobs through authenticated completion events.
• Keep concurrent jobs’ logs separate and provide runner-compatible log and timeline responses.
• Point gh at the emulator, enable notices, and use PATH-selected bash in Python steps.
Merge Risk 🟡 Medium

Blast radius 🔴 High 💥 4 capabilities

  • 4 affected capabilities span independent functional scopes: job_token_authentication, upstream_runner_job_observability, upstream_runner_step_execution, workflow_job_dependency_delivery.
  • The changed event stores a producer job's outputs and the existing completion path dispatches jobs whose needs are satisfied.
  • The producer, persistent output field, scheduler, and dependent job expression evaluation form one end-to-end dependency-delivery behavior, not separate capabilities.
  • Console feeds, uploaded step logs, and timeline state are distinct delivery surfaces for the same bounded end-to-end job-observability integration.
  • They share job-token routing and are consumed by the same upstream runner job UI/protocol.
  • gh API invocation, bash script execution, and workflow-command annotation rendering are separate user-visible step outcomes within the same bounded runner-execution integration.
  • They share the generated job request and step process, but each has a distinct failure outcome.
  • The changed expiry is a shared authentication behavior consumed by event, log, timeline, and other job-protocol routes.
  • It is an authentication integration scope, not a separate capability for each route.
Sources

src/runners/emulator/runner.py[1345-1347]

            shell_name = str(step.get("shell") or "bash")
            # Like actions/runner: bash from PATH, so a newer bash wins over /bin/bash.
            executable = (shutil.which("bash", path=env.get("PATH")) or "/bin/bash") if shell_name.split()[0] == "bash" else None

src/app/api/actions_distributed_task.py[589-592]

    # gh does not read GITHUB_API_URL. Without GH_HOST every gh call in a step
    # went to api.github.com with the emulator's token and failed with "Bad
    # credentials" (the Python runner sets it per step for the same reason).
    step_environment = {**oidc_environment, "GH_HOST": _gh_host(runner_base_url)}

src/app/api/actions_distributed_task.py[1386-1399]

    outputs = body.get("outputs", body.get("Outputs")) or {}
    resolved = {}
    for key, value in outputs.items():
        if isinstance(value, dict):
            if value.get("isSecret", value.get("IsSecret")):
                continue
            value = value.get("value", value.get("Value"))
        resolved[key] = "" if value is None else str(value)
    runner = (await db.execute(select(Runner).where(Runner.id == job.runner_id))).scalar_one_or_none()
    if runner is None:
        raise HTTPException(status_code=409, detail="Job has no runner to complete it")
    job.outputs = {**(job.outputs or {}), **resolved}
    await _complete_job(job, runner, body.get("result", body.get("Result", "Succeeded")), db)
    await db.commit()

src/app/api/actions_distributed_task.py[1498-1505]

def _next_step_log_id(job_id: int) -> int:
    directory = _step_log_dir(job_id)
    os.makedirs(directory, exist_ok=True)
    taken = [int(name.split(".")[0]) for name in os.listdir(directory) if name.split(".")[0].isdigit()]
    log_id = max(taken, default=0) + 1
    # Reserve the id now: the worker appends to it in a later request.
    open(os.path.join(directory, f"{log_id}.log"), "ab").close()
    return log_id

src/app/services/job_token_service.py[35-38]

def job_token_lifetime(job) -> int:
    """Seconds a job's token is valid: its timeout plus 5 minutes, capped at 24 h."""
    minutes = getattr(job, "timeout_minutes", None) or _DEFAULT_JOB_TIMEOUT_MINUTES
    return min(int(minutes) * 60 + _COMPLETION_MARGIN_SECONDS, _MAX_TOKEN_SECONDS)
Behavioral complexity 🔴 High 🧩 Concurrent ordering, Interacting branches

  • Before: step uploads were appended to the job log and the create response lacked the worker-required path.
  • After: creation reserves an ID, a later request appends by that ID, live console output remains separate, and the timeline response must use the worker's collection contract.
  • The new correctness condition is that the create-then-append protocol preserves a unique step-log identity under concurrent requests and that the two log streams do not duplicate or cross-contaminate records.
  • The changed behavior therefore introduces a resource-allocation ordering invariant; merely using filesystem helpers is not itself the complexity claim.
Sources

src/app/api/actions_distributed_task.py[1498-1505]

def _next_step_log_id(job_id: int) -> int:
    directory = _step_log_dir(job_id)
    os.makedirs(directory, exist_ok=True)
    taken = [int(name.split(".")[0]) for name in os.listdir(directory) if name.split(".")[0].isdigit()]
    log_id = max(taken, default=0) + 1
    # Reserve the id now: the worker appends to it in a later request.
    open(os.path.join(directory, f"{log_id}.log"), "ab").close()
    return log_id
Potential damage 🟡 Medium 🩹 Incorrect results

  • A wrong or incomplete producer output can cause dependent conditions, matrices, or command arguments to evaluate incorrectly.
  • Reverting code does not repair outputs already persisted or downstream jobs already promoted; recovery requires rerunning the producer and any affected dependents, or manual state repair.
  • The equal-importance baseline is used because no business-criticality declaration was supplied.
  • Usually recoverable by rerunning the producer and affected dependents; persisted outputs and already-triggered external effects are not automatically reverted.
Sources

src/app/api/actions_distributed_task.py[1386-1399]

    outputs = body.get("outputs", body.get("Outputs")) or {}
    resolved = {}
    for key, value in outputs.items():
        if isinstance(value, dict):
            if value.get("isSecret", value.get("IsSecret")):
                continue
            value = value.get("value", value.get("Value"))
        resolved[key] = "" if value is None else str(value)
    runner = (await db.execute(select(Runner).where(Runner.id == job.runner_id))).scalar_one_or_none()
    if runner is None:
        raise HTTPException(status_code=409, detail="Job has no runner to complete it")
    job.outputs = {**(job.outputs or {}), **resolved}
    await _complete_job(job, runner, body.get("result", body.get("Result", "Succeeded")), db)
    await db.commit()
Assessed commit d291354
Diagram

sequenceDiagram
    participant API as Protocol API
    participant Runner as Upstream Runner
    participant DB as Job Store
    participant Files as Log Files
    participant Scheduler as Job Scheduler
    API->>Runner: Job message and step environment
    Runner->>API: Console, logs, timeline updates
    API->>DB: Update token's job timeline
    API->>Files: Store job and step logs
    Runner->>API: JobCompleted with outputs
    API->>DB: Validate token and save completion
    API->>Scheduler: Release dependent jobs
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Persist step-log metadata in the database
  • ➕ Database-assigned IDs would avoid filesystem-based ID allocation across server processes.
  • ➖ Requires a schema and lifecycle changes for logs that are already stored as files.
2. Use verified job-token authentication across all job-server routes
  • ➕ Applies signature and expiry checks consistently beyond the new completion endpoint.
  • ➖ Broadens this protocol repair into an authentication migration requiring additional compatibility tests.

Recommendation: Keep the focused protocol changes: the upstream runner must send JobCompleted for outputs, and the existing file-backed logging model supports the immediate fix. Consider database-backed log IDs for multi-process deployment and shared verified authentication as a separate hardening effort.

Files changed (12) +732 / -73

Bug fix (2) +168 / -73
actions_distributed_task.pyComplete the upstream runner job-server protocol +166/-72

Complete the upstream runner job-server protocol

• Advertises and handles authenticated JobCompleted events, supplies output templates and plan version 8, and saves non-secret outputs before completing jobs. Routes logs and timeline updates by job token, separates uploaded step logs from console logs, and returns runner-compatible response shapes. Adds gh host/token step variables and enables enhanced annotations.

src/app/api/actions_distributed_task.py

runner.pyResolve bash from the step PATH +2/-1

Resolve bash from the step PATH

• Uses the bash executable found on the step PATH for bash steps, falling back to /bin/bash.

src/runners/emulator/runner.py

Tests (4) +437 / -0
test_execution.pyAssert gh host and notice capability in job messages +4/-0

Assert gh host and notice capability in job messages

• Extends the distributed-task protocol test to check the step GH_HOST and enhanced-annotations variable.

tests/actions/test_execution.py

test_runner_gh_host.pyTest upstream step host and token environments +86/-0

Test upstream step host and token environments

• Checks default-port handling, token-expression mirroring, absence of an invented token, and workflow-provided overrides.

tests/actions/test_runner_gh_host.py

test_runner_job_logs.pyTest per-job logs and timeline responses +159/-0

Test per-job logs and timeline responses

• Exercises concurrent jobs sharing a plan, distinct step-log IDs and paths, non-duplicated console logs, and collection-wrapped timeline responses.

tests/actions/test_runner_job_logs.py

test_runner_job_outputs.pyTest output events and completion safeguards +188/-0

Test output events and completion safeguards

• Checks resource discovery, output templates, plan version, secret filtering, and successful or failed completion. Also verifies that missing or invalid tokens, mismatched job IDs, and repeated events cannot change job results or outputs.

tests/actions/test_runner_job_outputs.py

Documentation (6) +127 / -0
PLAN.mdIndex five fixed runner bugs +5/-0

Index five fixed runner bugs

• Adds links to the fixed-bug notes for outputs, logging, gh, notices, and Python runner bash selection.

PLAN.md

gh-in-upstream-runner-steps-calls-github-com.mdDocument the upstream gh host and token fix +23/-0

Document the upstream gh host and token fix

• Explains why gh contacted GitHub instead of the emulator and records the host and token environment fix.

docs/bugs/fixed/gh-in-upstream-runner-steps-calls-github-com.md

notice-commands-stay-raw-on-the-upstream-runner.mdDocument notice-command enablement +23/-0

Document notice-command enablement

• Records the missing runner capability flag that left notice commands unrendered.

docs/bugs/fixed/notice-commands-stay-raw-on-the-upstream-runner.md

python-runner-uses-a-fixed-bash.mdDocument Python runner bash selection +18/-0

Document Python runner bash selection

• Explains the macOS bash compatibility problem and the switch to resolving bash from the step PATH.

docs/bugs/fixed/python-runner-uses-a-fixed-bash.md

upstream-runner-job-outputs-are-empty.mdDocument upstream job-output delivery +31/-0

Document upstream job-output delivery

• Identifies the missing output template, plan version, and event endpoint; describes how completion makes outputs available to dependent jobs.

docs/bugs/fixed/upstream-runner-job-outputs-are-empty.md

upstream-runner-logs-land-on-the-wrong-job.mdDocument job-log and timeline protocol fixes +27/-0

Document job-log and timeline protocol fixes

• Records cross-job log routing, missing log paths, and incompatible timeline responses, along with their fixes.

docs/bugs/fixed/upstream-runner-logs-land-on-the-wrong-job.md

@fullsend-ai-review

fullsend-ai-review Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 10:44 PM UTC · Completed 10:55 PM UTC

Commit: 6a2128d · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $5.05

@qodo-code-review

qodo-code-review Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Jobs longer than an hour never complete ✓ Resolved

Resolving commit: 58af4a8

Resolution reason
Job token lifetime is now computed from the job's timeout_minutes (default 360) plus a 5-minute
margin, capped at 24 hours, replacing the fixed 3600-second exp in issue_job_token. A job running
past an hour can therefore still report JobCompleted with a validly signed, unexpired token, and the
signature and expiry checks remain in place. A test covers completion after the one-hour boundary.
Description
dt_raise_plan_event rejects JobCompleted when validate_job_token finds that the token issued
with the job message has passed its one-hour exp, and the token is not renewed. For an upstream
job running longer than an hour under plan version 8, the only completion path returns 401, leaving
the job in_progress, its runner busy, and dependent jobs waiting for its outputs while other
job-server routes can still accept the token for logs and timeline access.

Grey Divider

Context sources
❌ Tickets: failed to load — Ticket collection could not establish complete evidence
✅ Compliance rules (platform): 6 rules
✅ Web pages:
  +4 more
✅ Cross-repo context — repo relationships
  Explored: repo: fullsend-ai/fullsend (sha: f28397f5) — View relationship
✅ Context preparation
  Commit messages: summarized; full text retained for this review
Review mode: Auto: 🧠 Deep: Multiple independent protocol, authentication, logging, output, and environment paths changed.

Grey Divider

Tip of the day
💡 Did you know, you can describe a rule in plain language on the Rules page and Qodo drafts it for you

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread src/app/api/actions_distributed_task.py Resolved
@fullsend-ai-review fullsend-ai-review Bot added the risk/moderate PR risk: moderate label Nov 18, 2026
@fullsend-ai-review

fullsend-ai-review Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Risk Assessment: moderate (2/5)

Details

Moderate risk change with 13 files and 867 lines touching runner protocol endpoints, balanced by zero protected path changes, no dependency modifications, 31% test file ratio, and alignment with linked tracking issue scope.

Previous run

Risk Assessment: moderate (2/5)

Details

Moderate risk change with 13 files and 867 lines touching runner protocol endpoints, balanced by zero protected path changes, no dependency modifications, 31% test file ratio, and alignment with linked tracking issue scope.

Previous run (2)

Risk Assessment: moderate (2/5)

Details

Moderate risk change with 12 files and 805 lines touching runner protocol endpoints, balanced by zero protected path changes, no dependency modifications, and 33% test coverage.

@fullsend-ai-review

fullsend-ai-review Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Review

Findings

Medium

  • [auth-bypass] src/app/api/actions_distributed_task.py:1525 — The timeline, console-feed and log routes take their job from _get_job_from_job_token. That calls _job_from_token_value, which only base64-decodes the JWT payload and looks up the sub claim. It never checks the HMAC signature, exp or nbf. An unauthenticated caller can forge a token with sub=job:<id> and change that job's step states, append console lines, or create and upload step logs. The new plan-events route calls validate_job_token, but these routes do not. The weakness is also in the base branch. This PR now makes these routes depend only on the helper and adds file-writing log endpoints behind it.
    Remediation: Make the shared helper call validate_job_token and reject invalid or expired tokens before selecting the job. Add forged-signature and expired-token rejection tests for the console-feed, log-create, log-upload and timeline-update routes.

  • [logic-error] src/app/services/job_token_service.py:34 — job_token_lifetime reads getattr(job, "timeout_minutes", None), but WorkflowJob has no timeout_minutes attribute. workflow_service.py puts the parsed value in the job dict and nothing stores it on the model. Every real job therefore gets the default 365-minute token lifetime, whatever its timeout-minutes. A job with a timeout above 360 minutes loses its token partway through the run. The new parameterized test passes SimpleNamespace objects that carry the attribute, so it never uses a real WorkflowJob.
    Remediation: Persist the configured timeout on WorkflowJob and set it during job creation. Test token issuance with a job created from workflow YAML that uses a non-default timeout.

Low

  • [logic-error] src/app/api/actions_distributed_task.py:777 — _with_gh_enterprise_token checks GH_ENTERPRISE_TOKEN and GITHUB_ENTERPRISE_TOKEN separately with setdefault. If a step sets GITHUB_ENTERPRISE_TOKEN=A and GH_TOKEN=B and leaves GH_ENTERPRISE_TOKEN unset, the function sets GH_ENTERPRISE_TOKEN=B. gh reads GH_ENTERPRISE_TOKEN first, so it uses B instead of A. The override test covers only GH_ENTERPRISE_TOKEN.
    Remediation: Skip mirroring when either enterprise variable is already present. Add a test with GITHUB_ENTERPRISE_TOKEN set alongside GH_TOKEN.

  • [code-organization] src/app/api/actions_distributed_task.py:1345 — dt_raise_plan_event imports validate_job_token inside the function, while issue_job_token from the same module is already imported at module level (line 40). There is no circular dependency.
    Remediation: Import validate_job_token next to issue_job_token at the top of the file and remove the inline import.

  • [backward-incompatible] src/app/api/actions_distributed_task.py — _job_request_message now sends plan.version 8 instead of 1. At version 8 the upstream runner no longer finishes the job request itself, so completion depends on the new dt_raise_plan_event endpoint receiving JobCompleted. A runner client that does not raise that event will never complete its jobs.

  • [backward-incompatible] src/app/api/actions_distributed_task.py — Distributed-task response shapes changed. The timeline update returns {count, value} instead of a bare array. Log create and append return a full TaskLog instead of {id, lineCount}. Octet-stream log create returns incrementing ids instead of always 1. Only the upstream runner is expected to consume these.

  • [backward-incompatible] src/app/api/actions_distributed_task.py — Job lookup no longer falls back to the plan id or timeline id on the console-feed, log and timeline routes; they use only the job token. Step logs go to a separate per-job directory. GH_HOST, the enterprise-token variables and DistributedTask.EnhancedAnnotations are now added to every step's environment or variables.


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR
Previous run

<!-- fullsend:review-findings-v2:eyJ2ZXJzaW9uIjoyLCJhY3Rpb24iOiJyZXF1ZXN0LWNoYW5nZXMiLCJmaW5kaW5ncyI6W3sic2V2ZXJpdHkiOiJtZWRpdW0iLCJjYXRlZ29yeSI6ImF1dGgtYnlwYXNzIiwiZmlsZSI6InNyYy9hcHAvYXBpL2FjdGlvbnNfZGlzdHJpYnV0ZWRfdGFzay5weSIsImlkIjoiZl8xMWUyMDg0YjQzZjlmOGQzIiwibGluZSI6MTUyNSwiYWN0aW9uYWJsZSI6dHJ1ZSwiZGltZW5zaW9uIjoic2VjdXJpdHkifSx7InNldmVyaXR5IjoibG93IiwiY2F0ZWdvcnkiOiJiYWNrd2FyZC1pbmNvbXBhdGlibGUiLCJmaWxlIjoic3JjL2FwcC9hcGkvYWN0aW9uc19kaXN0cmlidXRlZF90YXNrLnB5IiwiaWQiOiJmXzEyNWI1ZDRkOTBjZDVkYWM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Ijoib3BlbiJ9LHsiaWQiOiJmXzliNzI0MTY0MjhmY2Y3MzAiLCJzdGF0dXMiOiJvcGVuIn1dfQ== -->

Review

Findings

Medium

  • [auth-bypass] src/app/api/actions_distributed_task.py:1525 — The timeline endpoint (and the console-feed and log endpoints) still authenticate through _job_from_token_value, which only decodes the JWT payload's job:<id> subject. The signature and expiry are not checked, so a forged token naming any existing job can change that job's step states or append logs. The new plan-events endpoint does verify the signature with validate_job_token; these routes don't. This PR makes the token the only job selector on them.
    Remediation: Make _job_from_token_value use validate_job_token (signature and expiry), keeping the Bearer/Basic challenge behaviour. Add negative tests with forged and expired tokens against the timeline, console-feed, log-creation and log-upload endpoints.

Low

  • [backward-incompatible] src/app/api/actions_distributed_task.py — Log endpoints now return a full TaskLog with a server-allocated id, step logs go to per-log files, and the plan-based job lookup fallback was removed. Intentional.
  • [backward-incompatible] src/app/api/actions_distributed_task.py — Timeline record updates now return {count, value} instead of a bare array. Intentional.
  • [backward-incompatible] src/app/api/actions_distributed_task.py — Job message: plan version is now 8, so completion depends on the new plan-events endpoint. It also adds jobOutputs, EnhancedAnnotations, and GH_HOST/GH_ENTERPRISE_TOKEN in every step. Intentional.

Earlier findings

  • src/app/api/actions_distributed_task.py:1348, edge-case — resolved: the job token now lasts the job's timeout plus 5 minutes (capped at 24 h) in job_token_service.py, and test_the_job_token_lasts_as_long_as_the_job covers completion after two hours and rejection after seven.

Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR
Previous run (2)

<!-- fullsend:review-findings-v2:eyJ2ZXJzaW9uIjoyLCJhY3Rpb24iOiJyZXF1ZXN0LWNoYW5nZXMiLCJmaW5kaW5ncyI6W3sic2V2ZXJpdHkiOiJtZWRpdW0iLCJjYXRlZ29yeSI6ImVkZ2UtY2FzZSIsImZpbGUiOiJzcmMvYXBwL2FwaS9hY3Rpb25zX2Rpc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ZhbHNlLCJkaW1lbnNpb24iOiJjcm9zcy1yZXBvLWNvbnRyYWN0cyJ9XX0= -->

Review

Findings

Medium

  • [edge-case] src/app/api/actions_distributed_task.py:1348 — Jobs that run longer than one hour can no longer complete. issue_job_token() sets exp = now + 3600 and validate_job_token() rejects expired tokens, so a JobCompleted event sent after the token expires gets 401. The job message now declares plan version 8, so the upstream listener skips the finish-request call and nothing else completes the job. It stays in_progress, its runner stays busy, and jobs that needs: it stay blocked.
    Remediation: Give the job token a lifetime that covers the longest supported job plus completion retries, or add renewal that the upstream worker actually uses. Add a time-controlled test that completes a job after more than an hour.

  • [auth-bypass] src/app/api/actions_distributed_task.py:1525 — _get_job_from_job_token calls _job_from_token_value, which decodes sub from the JWT payload and loads that job without checking signature or expiry. A forged Bearer token with sub = job:<victim-id> can change that job's step statuses, write to its console log, or create and append its step logs. This PR makes the token the only selector of the job on the timeline, feed, create-log and append-log routes. The weakness predates the PR, but JobCompleted now validates the token while these routes don't.
    Remediation: Call validate_job_token in the shared job-token helper and return 401 for a bad signature or expired token before loading the job. Add forged-signature and expired-token tests. Pair this with the token-lifetime fix above so long jobs don't start failing mid-run.

Low

  • [backward-incompatible] src/app/api/actions_distributed_task.py — Uploaded step logs (create-log and append-log) no longer go into the job log file. They go to a separate <job_id>/<log_id>.log file that nothing reads. The create-log and append-log responses changed shape from {id, lineCount} to a full TaskLog with path, and ids are now allocated server-side.

  • [backward-incompatible] src/app/api/actions_distributed_task.py — The timeline records PATCH response changed from a bare array to {count, value}. The feed, create-log, append-log and timeline endpoints also no longer fall back to the URL plan-id/timeline-id to pick the job; the job named in the job token is now the only selector.

  • [backward-incompatible] src/app/api/actions_distributed_task.py — Every upstream-runner step now gets GH_HOST set to the emulator's host. Steps that name GH_TOKEN or GITHUB_TOKEN also get GH_ENTERPRISE_TOKEN and GITHUB_ENTERPRISE_TOKEN. Workflows that deliberately point gh at github.com now reach the emulator unless they override GH_HOST. This is intentional and is recorded only in the bug notes.


Labels: PR fixes upstream-runner protocol bugs


Next steps:

  • /fs-fix — agent addresses review findings automatically
  • /fs-fix <your instruction> — agent fixes with your specific guidance
  • Push commits directly — review re-runs automatically on push
  • /fs-fix-stop — disable automatic fix runs for this PR

fullsend-ai-review[bot]

This comment was marked as outdated.

@fullsend-ai-review fullsend-ai-review Bot added the bug Something isn't working label Nov 18, 2026
@waynesun09

Copy link
Copy Markdown
Member Author

On the three low notes:

  • Per-job step logs and the TaskLog response shape: both are what the upstream worker expects. Its TaskLog requires a path, and ids are allocated by the server, as on GitHub.
  • {count, value} for timeline updates: the worker reads that collection wrapper and treated the bare array as a failed update.
  • The job token as the job selector: a plan is the whole run, so the URL could not tell two running jobs apart.
  • GH_HOST in every step: this is the point of the change. A workflow that wants github.com sets its own GH_HOST, which wins.

All of this is in the bug notes.

@fullsend-ai-review

fullsend-ai-review Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 11:05 PM UTC · Completed 11:16 PM UTC

Commit: 58af4a8 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $2.22

fullsend-ai-review[bot]

This comment was marked as outdated.

@jctanner jctanner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving with nits — with one merge-order requirement: this must land after #31 (or adopt its validate_job_token in _job_from_token_value), because at this head the timeline/log/feed routes still accept forged job tokens while the new plan-events route does verify them. Everything else checks out: plan v8 + jobOutputs + the events resource, per-job logs with real paths, {count, value} timeline answers, GH_HOST mirroring, EnhancedAnnotations, and the job-token lifetime fix (which also resolves #31's long-job expiry finding). Nits: the two event tests the bot asked for are there; consider a follow-up for the bash-PATH lookup having no dedicated test.

@waynesun09
waynesun09 force-pushed the emu-03-runner-protocol branch from 58af4a8 to 3ed7592 Compare November 19, 2026 17:20
@fullsend-ai-review

fullsend-ai-review Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 5:23 PM UTC · Completed 5:35 PM UTC

Commit: 3ed7592 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $4.15

@fullsend-ai-review fullsend-ai-review 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.

See the review comment for full details.

Comment thread src/app/api/actions_distributed_task.py Resolved
Comment thread src/app/services/job_token_service.py Resolved
Comment thread src/app/api/actions_distributed_task.py Resolved
Comment thread src/app/api/actions_distributed_task.py Resolved
The upstream runner evaluates a job's outputs: itself and reports them
only in the JobCompleted plan event, so on that path every
needs.<job>.outputs.<name> rendered empty:

- the job message carried no jobOutputs template;
- it declared plan version 1, and the worker raises JobCompleted only
  from plan version 8 (PlanUtil.GetFeatures);
- the plan events resource was neither advertised nor served.

Send the declared outputs as a jobOutputs template, declare plan
version 8, and serve the plan events resource. JobCompleted, accepted
from the job's own token, stores the job's non-secret outputs and then
completes the job: at version 8 the listener no longer finishes the job
request, so this releases the jobs that need it with the outputs in
place.

The event route checks the job token's signature and expiry
(validate_job_token), and takes the event only for a job in progress:
a repeat after completion, or an event for a job queued again, changes
neither its outputs nor its result.

Assisted-by: Claude
Signed-off-by: Wayne Sun <gsun@redhat.com>
- Find the job from the job token, not from the plan. A plan is the whole
  run, so with two jobs running one job's console lines and step states
  went to the other, and the first job's log was missing.
- Answer log creation with the log's path and a distinct id. The worker's
  TaskLog requires a path, so every step-log upload threw.
- Keep uploaded step logs in their own files beside the job log, which
  the console feed already writes, so lines are not doubled.
- Answer timeline updates with {count, value}. The worker reads a
  collection wrapper and treated a bare array as a failed update.

Assisted-by: Claude
Signed-off-by: Wayne Sun <gsun@redhat.com>
gh ignores GITHUB_API_URL, so on the upstream-runner path every gh call
in a step went to api.github.com with the emulator's job token and
failed with "Bad credentials". Set GH_HOST for every step, and mirror
the token the step chose (GH_TOKEN or GITHUB_TOKEN, as the same
expression) into GH_ENTERPRISE_TOKEN, which gh reads for any host but
github.com. No token is added to a step that named none, and what a
workflow sets itself wins. The Python runner already does both.

Assisted-by: Claude
Signed-off-by: Wayne Sun <gsun@redhat.com>
The Python runner always used /bin/bash. On macOS that is bash 3.2,
which rejects bash 4 syntax (;;&, ${var,,}) that GitHub-hosted runners
accept. actions/runner resolves bash from PATH; do the same and fall
back to /bin/bash.

Assisted-by: Claude
Signed-off-by: Wayne Sun <gsun@redhat.com>
actions/runner processes `::notice::` only when the job message turns on
DistributedTask.EnhancedAnnotations (ActionCommandManager: "Enhanced
Annotations not enabled on the server: 'notice' command will not be
processed"). GitHub sends it, and documents notice as a workflow command
beside warning and error. The emulator did not, so on the upstream
runner a `::notice::text` line stayed raw in the job log instead of
`##[notice]text`, while `::warning::` and `::error::` rendered. The
emulator's own Python runner already renders all three.

The job request message now sets the variable to "true".

Assisted-by: Claude
Signed-off-by: Wayne Sun <gsun@redhat.com>
GitHub's job token is valid until the job ends. Here it expired an hour
after it was issued, and from plan version 8 only the JobCompleted event
completes a job, so a job that ran longer than an hour reported its
completion with an expired token, got 401, and stayed in progress with
its runner busy.

The token now lives for the job's timeout-minutes (default 360) plus 5
minutes for the completion report, at most 24 hours. The job's timeout
is not stored with the job, so the default applies.

Assisted-by: Claude
Signed-off-by: Wayne Sun <gsun@redhat.com>
Rebased onto #31, every other job-server route answers 404 for a plan that is not the job's own run; the plan events route now does too. validate_job_token comes from the module-level import #31 added. #31's route-target test counts the per-step log files this change writes, since uploads no longer append to the console log.

Assisted-by: Claude
Signed-off-by: Wayne Sun <gsun@redhat.com>
@fullsend-ai-review

fullsend-ai-review Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

🤖 Finished Review · ✅ Success · Started 6:01 PM UTC · Completed 6:26 PM UTC

Commit: d291354 · View workflow run →

Runtime: pi · Model: sonnet → claude-sonnet-5-5 · Effort: high · Cost: $0.53

@waynesun09
waynesun09 merged commit 69c2a2b into main Nov 19, 2026
62 of 64 checks passed
@waynesun09
waynesun09 deleted the emu-03-runner-protocol branch November 19, 2026 18:21
waynesun09 added a commit that referenced this pull request Nov 19, 2026
#34's plan-events route completed only a job still in progress. A job
cancelled while it ran is already completed, so its JobCompleted event
returned early and its runner stayed busy for good. A cancelled job now
reaches _complete_job too, which keeps the cancelled conclusion and
frees the runner; its outputs are left unchanged. A queued job, or a
job completed otherwise, still returns early.

The report goes through _report_job_end, so it runs under the runner's
lock and leaves a job that moved off the runner as it is, as the other
report routes do.

Test: test_job_completed_for_a_cancelled_job_frees_the_runner, from the
combined validation branch.

Assisted-by: Claude
Signed-off-by: Wayne Sun <gsun@redhat.com>
@fullsend-ai-review

Copy link
Copy Markdown

Review skipped — this PR is already merged.

The /fs-review command only reviews open PRs/MRs.

Posted by fullsend post-review check

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

Labels

bug Something isn't working risk/moderate PR risk: moderate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants