Skip to main content
← Back to list
01Issue
BugShippedSwamp CLIPublicTeam
Assigneeszack

Relationships

#3958 swamp serve: a workflow run interrupted at a clean shutdown stays `running` in the shared S3 datastore when the 5 s interrupt push misses its deadline; boot and peer reapers do not settle it there

Opened by vcjdeboer · 10/26/2026· Shipped 10/26/2026

Summary

swamp serve is stopped cleanly (SIGTERM) on an S3 datastore while a workflow run is in flight. It drains, aborts and marks the run interrupted locally. It then pushes that record under one 5 s deadline, which covers both the shared sync gate and the upload. If the push misses the deadline, serve only logs a warning and exits, and the shared datastore keeps the run's last pushed state: running. The instance has deleted its heartbeat, so continuous reconciliation on other instances never treats it as dead. Any reader on another cache sees the run running with its step still running:

  • another machine or checkout;
  • a new serve host;
  • an HA peer.

A serve that hydrates a fresh cache reaps the run ("tracker confirmed stale"). That reap is saved with no push, so the datastore copy is still running afterwards. In the local reproduction the restarted original instance shows interrupted from its own cache, and the datastore is corrected only when that same instance happens to push something later, which may never happen. In production (below) it was worse: the restarted serve itself skipped the run at boot and kept serving it as running.

We observed this in production on AWS S3: a run stayed running after a planned, clean systemctl restart of swamp serve, and only an admin workflow cancel settled it (see "Observed on AWS S3 (production)"). It also happened before #3252 was fixed. The fix for #3252 added the push, but the push still fails silently when the datastore is slow at shutdown.

Environment

  • swamp 20261012.111134.0-sha.8a1aa395 (darwin-aarch64 release binary, checksum verified). Reproduced.
  • swamp 20261026.014016.0-sha.7e1aad04, the newest release at the time of writing. Reproduced the same way.
  • Also on hand, not run in the repro: swamp 20261006.231101.0-sha.9a8ec977.
  • @swamp/s3-datastore 2026.10.01.1 (with 8a1aa395) and 2026.10.24.2 (with 7e1aad04).
  • S3: a local, stateful, path-style S3 endpoint (fake_s3.py, standard library only). It is a port of the extension's own test emulator (datastore/s3/extensions/datastores/_lib/s3_emulator_test_util.ts). Like holdPut, it can hold each PutObject before it commits, and it commits nothing when the client gives up. No AWS account is needed.
  • macOS 26 (Darwin 25.2), arm64. Default serve settings, except --auth-mode left at its default (none) and --log-level info.

Reproduction

The scripts are inlined at the end of this issue ("Reproduction scripts"). Each one says what it needs at the top.

  1. zsh setup.sh <swamp> sets up a throwaway environment:
    • starts fake_s3.py on 127.0.0.1:9555;
    • makes a throwaway repo with @swamp/s3-datastore pointed at it ({"bucket":"repro-bucket","endpoint":"http://127.0.0.1:9555","forcePathStyle":true});
    • creates a command/shell model sleeper;
    • adds a workflow slow (workflow-slow.yaml) with three steps: first (echo first), then sleep (sleep 120), then after (echo done).
  2. zsh repro.sh <swamp> 8 <label>:
    1. Starts swamp serve.
    2. Starts swamp workflow run slow --server ws://127.0.0.1:9190.
    3. Waits until step sleep is running.
    4. Makes the datastore slow, holding every PutObject 8 s.
    5. Sends SIGTERM to serve and waits for it to exit.
    6. Makes the datastore fast again and restarts serve on the same cache.
    7. Polls workflow history get through the new serve every 30 s for 4.5 minutes.
    8. Reads the run's object in the bucket, then reads the run through a fresh cache (fresh-reader.sh: a new SWAMP_HOME, datastore sync --pull, workflow history get).
    9. Lists _control/active-runs/ and _control/heartbeats/.
  3. zsh repro.sh <swamp> 0 control is the control, with no delay.
  4. zsh fresh-serve.sh <swamp> <run id> starts a second serve on a fresh cache and reads the run. It then waits 70 s, past a reconciliation interval, and reads the bucket again.
  5. zsh later-write.sh <swamp> <run id> restarts the original serve on its own cache, runs one unrelated method through it, and reads the bucket again.

Expected

A cleanly stopped serve leaves no workflow run running in the shared datastore. Either the interrupted record reaches the datastore before exit, with the deadline enforced and retried, or a later reaper settles the run in the datastore rather than only in its own cache.

Actual

These are the transcripts in repro/logs/, from 8a1aa395 with the 8 s hold. 7e1aad04 gives the same result (logs/latest-delay-serve-*.txt).

09:29:38 before restart: running [('first', 'succeeded'), ('sleep', 'running'), ('after', 'pending')]
09:29:38 SIGTERM serve 1
09:30:18 serve 1 exited 0
09:30:21 after restart: interrupted [('first', 'succeeded'), ('sleep', 'unknown'), ('after', 'pending')]   <- the restarted instance's own cache
...  (unchanged every 30 s for 4.5 min)
09:35:01 the shared datastore's copy of the run: status: running
fresh cache reads: running [('first', 'succeeded'), ('sleep', 'running'), ('after', 'pending')]
09:35:05 control-plane active-run records left: _control/active-runs/<dead instance id>/<run id>
09:35:05 heartbeats left: (none)

The serve log of the stopped instance:

Shutting down, draining in-flight runs for up to 30s...
Draining 1 active run(s)...
Aborting 1 undrained run(s)...
Interrupted workflow run "<run id>" (server shutdown)
Failed to push interrupted workflow run(s) [ "<run id>" ] to the datastore; their interrupted status was not saved there: "timed out after 5000ms"

A second serve on a fresh cache (fresh-serve.sh):

Hydrating local cache from remote datastore
Pulled 17 file(s) from remote datastore
Boot: reaping stale runs via tracker
Reaped stale "workflow" run "<run id>" ("slow")
Reaping orphaned workflow run "<run id>" (workflow: "slow", reason: "tracker confirmed stale")
history get through it: interrupted      <- only in its cache
the shared datastore's copy: status: running

The original instance heals the datastore only on its next push (later-write.sh: one unrelated model method run, then the bucket shows interrupted). If that instance never writes again, the record stays running. That happens when the host is replaced, the cache is lost, or traffic moves to another instance.

The control (no hold) is clean: the bucket shows interrupted, a fresh cache reads interrupted (sleep failed, after skipped), and no active-run record is left.

Observed on AWS S3 (production)

A real sitting on 2026-10-26, separate from the local reproduction above:

  • swamp serve 20261012.111134.0-sha.8a1aa395 under systemd on an EC2 instance (Linux), with an @swamp/s3-datastore datastore on AWS S3 in eu-north-1. Clients reach it over --server.
  • One workflow run was in flight, at a long-running step, when the serve was stopped with a clean systemctl restart (SIGTERM, inside the unit's stop timeout; no SIGKILL).

What the serve's journal (persistent systemd journal) showed:

  1. The drain started ("Shutting down, draining in-flight runs …"); one run was left undrained.
  2. Serve aborted it and logged it interrupted (Interrupted workflow run "<run id>" (server shutdown)).
  3. The push failed on the deadline: Failed to push interrupted workflow run(s) [ "<run id>" ] to the datastore; their interrupted status was not saved there: "timed out after 5000ms".
  4. After the restart, the boot reaper skipped that run (the tracker still listed it as running) and reaped none.

What clients saw:

  • The restarted serve served the run as running, at its last step still running, still at the end of our check's settle window. So in production the restarted instance itself did not settle the run, not even in its own cache; this goes further than the local reproduction, where the restarted instance showed interrupted from its cache.
  • An admin swamp workflow cancel <workflow> --run <run id> through the restarted serve settled it as cancelled.
  • The run's other records (step outputs, data written before the restart) were intact afterwards.

Nothing slowed the datastore artificially here: against real S3, the single 5 s deadline (which also covers the wait for the shared sync gate) was missed.

Source analysis

Line numbers are given as 8a1aa395 / 7e1aad04.

  1. The push of the interrupted runs is best effort, with one 5 s deadline.
    • src/serve/shutdown_interrupt.ts:45 (both): SHUTDOWN_PUSH_TIMEOUT_MS = 5_000.
    • :149: Promise.race([push, deadline]) covers both the wait for the shared sync gate (withSharedSyncGate) and the upload.
    • :153: on a miss it only logs "their interrupted status was not saved there", and interruptShutdownRuns returns normally.
    • The shutdown in src/cli/commands/serve.ts:6771 / :7216 goes on. Nothing retries and nothing records the miss for the next boot.
  2. The heartbeat is deleted on a clean stop.
    • src/cli/commands/serve.ts:6795 / :7244 calls heartbeatService.stop().
    • That runs src/serve/instance_heartbeat.ts:95 (both): delete(heartbeats/<instanceId>).
    • reconcileRemoteInterruptedRuns (src/serve/boot_reconciliation.ts) acts only on instances with a stale heartbeat, so a cleanly stopped instance is never reconciled. Its _control/active-runs/<instance>/<run> record also stays.
  3. The boot reaper saves without a push.
    • src/cli/commands/serve.ts:4366-4376 / :4740-4750: "The boot reap ... run[s] in root units of work with no push ... Nothing pushes, as before."
    • It calls reapOrphanedWorkflowRuns with { flush: undefined }.
    • src/domain/workflows/orphaned_run_reaper.ts:79 (both) interrupts the run ("tracker confirmed stale") in the local cache only.
    • The YAML reap in reconcileRemoteInterruptedRuns is the same: src/serve/boot_reconciliation.ts:623 / :672,721 (flush: undefined) and :633 / :734 (interruptOrphaned("remote_instance_dead")), with no push (swamp-club#3056).
  4. The reaper skips a run the tracker still lists as running. src/domain/workflows/orphaned_run_reaper.ts:66-72 (both): "Skipping workflow run … tracker reports still running". Any instance whose tracker row was not settled at shutdown leaves the run as it is.

Together:

  • The only write that would settle the run in the shared datastore is the 5 s best-effort push.
  • Every later settlement (boot reap, peer reap, the restarted owner's cache) is local until something unrelated pushes.
  • The cleanly stopped instance has deleted the only signal (its heartbeat) that would make a peer settle it.

Suggested fix

Choose one or more:

  1. Make the shutdown push durable.
    • Bound the gate wait and the upload separately.
    • Retry within serve's own stop budget. systemd's default TimeoutStopSec is 90 s, against a 30 s drain plus a 5 s grace.
    • On a final miss, keep a local "unpushed interrupt" marker. The next boot pushes it before it serves, or as part of the required hydration.
  2. Push what the reapers settle. The boot reap and reconcileRemoteInterruptedRuns should push their interrupted saves (one batched push after the reap), so the shared datastore converges. It should not wait for an unrelated later write.
  3. Leave a tombstone instead of nothing. On a clean stop, do not delete the heartbeat while runs of the instance are still running in the datastore. Alternatively, write a "stopped" heartbeat, so peers' continuous reconciliation treats those runs as orphaned and settles them in the datastore. Clean up the instance's _control/active-runs/<instance>/ records at the same time.
  4. Make the failure visible. serve could exit non-zero, or emit a JSON status ({"status":"interrupt_push_failed","runIds":[…]}) in --json mode, so an operator or a supervisor knows the datastore holds a stale run.

Workaround

An admin runs swamp workflow cancel <workflow> --run <id> through any serve instance. For a run with no live owner, the persisted cancel path (src/serve/suspended_run_cancel.ts) settles it and pushes.

Reproduction scripts

Place them in one directory. fake_s3.py uses only the Python standard library. Nothing touches AWS.

env.sh
# throwaway environment for the stale-run reproduction (local fake S3, no AWS)
export SWAMP_HOME=/tmp/repro-swamp/home
export SWAMP_NO_TELEMETRY=1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
export AWS_REGION=us-east-1
unset AWS_PROFILE AWS_SESSION_TOKEN
export SW=${SW:-swamp}
export R=/tmp/repro-swamp/repo
# swamp needs a swamp-club sign-in; with SWAMP_HOME set, the config (sign-in)
# would move under it, so point SWAMP_CONFIG_DIR back at your normal one
export SWAMP_CONFIG_DIR=$HOME/.config/swamp
setup.sh
#!/bin/zsh
# Fresh throwaway repo on a fresh fake S3 bucket. Usage: setup.sh <swamp binary>
# Starts fake_s3.py (127.0.0.1:9555) and makes repo $R with @swamp/s3-datastore
# pointed at it, model `sleeper` (command/shell) and workflow `slow`.
set -u
export SW=$1
. ${0:A:h}/env.sh
D=${0:A:h}
pkill -f "fake_s3.py 9555" ; sleep 1
rm -rf $R $SWAMP_HOME /tmp/repro-swamp/ctl; mkdir -p $R $SWAMP_HOME /tmp/repro-swamp/ctl
nohup python3 -I $D/fake_s3.py 9555 /tmp/repro-swamp/ctl > /tmp/repro-swamp/s3.log 2>&1 &
sleep 1
cd $R
$SW repo init >/dev/null 2>&1 || exit 1
$SW extension pull ${EXT:-@swamp/s3-datastore@2026.10.01.1} --repo-dir $R >/dev/null 2>&1 || exit 1
$SW datastore setup extension @swamp/s3-datastore --repo-dir $R \
  --config '{"bucket":"repro-bucket","region":"us-east-1","endpoint":"http://127.0.0.1:9555","forcePathStyle":true}' >/dev/null 2>&1 || exit 1
$SW model create command/shell sleeper --repo-dir $R >/dev/null 2>&1 || exit 1
cp $D/workflow-slow.yaml $R/workflows/workflow-00000000-0000-4000-8000-000000000001.yaml
$SW workflow validate slow --repo-dir $R 2>&1 | tail -1
workflow-slow.yaml
id: 00000000-0000-4000-8000-000000000001
name: slow
description: a short step, a step that sleeps, then a short step
jobs:
  - name: main
    steps:
      - name: first
        task:
          type: model_method
          modelIdOrName: sleeper
          methodName: execute
          inputs:
            run: echo first
        dependsOn: []
        weight: 0
        allowFailure: false
      - name: sleep
        task:
          type: model_method
          modelIdOrName: sleeper
          methodName: execute
          inputs:
            run: sleep 120
        dependsOn:
          - step: first
            condition:
              type: succeeded
        weight: 0
        allowFailure: false
      - name: after
        task:
          type: model_method
          modelIdOrName: sleeper
          methodName: execute
          inputs:
            run: echo done
        dependsOn:
          - step: sleep
            condition:
              type: succeeded
        weight: 0
        allowFailure: false
repro.sh
#!/bin/zsh
# Reproduction: a workflow run in flight across a clean (SIGTERM) restart of
# `swamp serve` on an S3 datastore whose writes are slow at shutdown.
# Usage: repro.sh <swamp binary> <put delay seconds, 0 = control> <label>
# Needs: fake_s3.py on 127.0.0.1:9555 (ctl dir $CTL), a repo $R set up with
# @swamp/s3-datastore against it, model `sleeper` (command/shell) and workflow
# `slow` (workflow-slow.yaml). Nothing here touches AWS.
set -u
SW=$1 DELAY=$2 LABEL=$3
. ${0:A:h}/env.sh
export SW
CTL=/tmp/repro-swamp/ctl
OUT=/tmp/repro-swamp/out-$LABEL; rm -rf $OUT; mkdir -p $OUT
PORT=9190 URL=ws://127.0.0.1:9190
ts() { date -u +%H:%M:%S; }
rm -f $CTL/put-delay
start_serve() {   # <n>
  $SW serve --repo-dir $R --host 127.0.0.1 --port $PORT --log-level info > $OUT/serve-$1.log 2>&1 &
  SERVE=$!
  for i in {1..60}; do curl -sf -m 2 http://127.0.0.1:$PORT/ready >/dev/null && { echo "$(ts) serve $1 ready (pid $SERVE)"; return 0; }; sleep 1; done
  echo "$(ts) serve $1 not ready"; return 1
}
status() {   # <run id> -> prints status and step statuses
  $SW workflow history get $1 --server $URL --json 2>/dev/null | python3 -I -c '
import json,sys
d=json.load(sys.stdin); r=d.get("run") if isinstance(d.get("run"),dict) else d
steps=[(s.get("name"),s.get("status")) for j in r.get("jobs") or [] for s in j.get("steps") or []]
print(r.get("status"), steps)'
}
echo "$(ts) $($SW --version 2>&1 | tail -1); put delay at shutdown: $DELAY s"
start_serve 1 || exit 1
$SW workflow run slow --server $URL --json > $OUT/client.json 2>&1 &
CLIENT=$!
WR=""
for i in {1..60}; do
  WR=$($SW workflow history search slow --server $URL --json 2>/dev/null | python3 -I -c '
import json,sys
d=json.load(sys.stdin); rs=d.get("runs") or d.get("results") or []
rs=[x for x in rs if x.get("status")=="running"]
print(rs[0].get("runId") or rs[0].get("id") if rs else "")')
  [[ -n $WR ]] && break; sleep 1
done
echo "$(ts) workflow run $WR"
sleep 15; for i in {1..60}; do s=$(status $WR); [[ $s == *"('sleep', 'running')"* ]] && break; sleep 1; done
echo "$(ts) before restart: $s"
[[ $DELAY != 0 ]] && echo $DELAY > $CTL/put-delay
echo "$(ts) SIGTERM serve 1"
kill -TERM $SERVE
wait $SERVE; echo "$(ts) serve 1 exited $?"
rm -f $CTL/put-delay
wait $CLIENT 2>/dev/null
start_serve 2 || exit 1
for i in {1..9}; do echo "$(ts) after restart: $(status $WR)"; sleep 30; done
kill -TERM $SERVE; wait $SERVE
echo "$(ts) the shared datastore's copy of the run: $(curl -s http://127.0.0.1:9555/repro-bucket/workflow-runs/00000000-0000-4000-8000-000000000001/workflow-run-$WR.yaml | grep -m1 '^status:')"
echo "$(ts) through a fresh cache (another host or a new serve host):"
zsh ${0:A:h}/fresh-reader.sh $SW $WR
echo "$(ts) control-plane active-run records left: $(curl -s 'http://127.0.0.1:9555/repro-bucket?list-type=2&prefix=_control/active-runs/' | grep -o '<Key>[^<]*</Key>' | tr '\n' ' ')"
echo "$(ts) heartbeats left: $(curl -s 'http://127.0.0.1:9555/repro-bucket?list-type=2&prefix=_control/heartbeats/' | grep -o '<Key>[^<]*</Key>' | tr '\n' ' ')"
echo "$(ts) done; logs in $OUT"
fresh-reader.sh
#!/bin/zsh
# Read a workflow run's status through a FRESH cache of the same datastore
# (a second machine, a new serve host, or an HA peer): a new SWAMP_HOME,
# same repository and datastore config. Usage: fresh-reader.sh <swamp> <run id>
set -u
export SW=$1
. ${0:A:h}/env.sh
export SWAMP_HOME=/tmp/repro-swamp/home-fresh-$$
mkdir -p $SWAMP_HOME
cd $R
$SW datastore sync --pull --repo-dir $R >/dev/null 2>&1
$SW workflow history get $2 --repo-dir $R --json 2>$SWAMP_HOME.err | python3 -I -c '
import json,sys
d=json.load(sys.stdin); r=d.get("run") if isinstance(d.get("run"),dict) else d
print("fresh cache reads:", r.get("status"), [(s.get("name"), s.get("status")) for j in r.get("jobs") or [] for s in j.get("steps") or []])'
tail -5 $SWAMP_HOME.err; rm -rf $SWAMP_HOME $SWAMP_HOME.err
fresh-serve.sh
#!/bin/zsh
# A second `swamp serve` on a FRESH cache of the same datastore (a new serve
# host, or an HA peer): it hydrates, reaps the run locally, and pushes nothing.
# Usage: fresh-serve.sh <swamp binary> <run id>
set -u
export SW=$1
. ${0:A:h}/env.sh
export SWAMP_HOME=/tmp/repro-swamp/home-fresh-serve
rm -rf $SWAMP_HOME; mkdir -p $SWAMP_HOME
cd $R
$SW serve --repo-dir $R --host 127.0.0.1 --port 9191 --log-level info > /tmp/repro-swamp/fresh-serve.log 2>&1 &
S=$!
for i in {1..60}; do curl -sf -m 2 http://127.0.0.1:9191/ready >/dev/null && break; sleep 1; done
$SW workflow history get $2 --server ws://127.0.0.1:9191 --json 2>&1 | grep -m1 '"status"'
sleep 70
$SW workflow history get $2 --server ws://127.0.0.1:9191 --json 2>&1 | grep -m1 '"status"'
kill -TERM $S; wait $S
grep -E "Hydrating|Pulled|reaping|Reaping|Reaped" /tmp/repro-swamp/fresh-serve.log
sleep 5
echo "the shared datastore's copy: $(curl -s http://127.0.0.1:9555/repro-bucket/workflow-runs/00000000-0000-4000-8000-000000000001/workflow-run-$2.yaml | grep -m1 '^status:')"
later-write.sh
#!/bin/zsh
# Does a later write through the restarted serve (its cache holds the
# interrupted record) carry that record to the datastore?
# Usage: later-write.sh <swamp binary> <run id>
set -u
export SW=$1
. ${0:A:h}/env.sh
cd $R
$SW serve --repo-dir $R --host 127.0.0.1 --port 9190 --log-level info > /tmp/repro-swamp/later-write.log 2>&1 &
S=$!
for i in {1..60}; do curl -sf -m 2 http://127.0.0.1:9190/ready >/dev/null && break; sleep 1; done
$SW model method run sleeper execute --input 'run=echo later' --server ws://127.0.0.1:9190 --json > /dev/null 2>&1
echo "method run exit $?"
sleep 20
kill -TERM $S; wait $S
echo "the shared datastore's copy after a later write: $(curl -s http://127.0.0.1:9555/repro-bucket/workflow-runs/00000000-0000-4000-8000-000000000001/workflow-run-$2.yaml | grep -m1 '^status:')"
fake_s3.py
#!/usr/bin/env python3
"""A minimal, stateful, path-style S3 endpoint (standard library only) for a
throwaway swamp serve on a remote datastore. A port of the s3 datastore
extension's own test emulator (swamp-extensions datastore/s3
_lib/s3_emulator_test_util.ts): GET/HEAD/PUT (If-Match, If-None-Match)/COPY/
DELETE objects, ListObjectsV2 (with and without delimiter), HeadBucket.
Signatures are not checked.

Fault injection: while the file <ctl>/put-delay holds a number N, every
PutObject and CopyObject waits N seconds before it commits (a slow
datastore). Every request is logged to stderr with its time.

Usage: python3 -I fake_s3.py <port> <ctl dir>"""
import os
import sys
import threading
import time
import uuid
from datetime import datetime, timezone
from email.utils import formatdate
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, unquote, urlparse

OBJECTS = {}
LOCK = threading.Lock()
CTL = sys.argv[2]


def esc(s):
    return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def put_delay():
    try:
        with open(os.path.join(CTL, "put-delay")) as f:
            return float(f.read().strip() or 0)
    except (OSError, ValueError):
        return 0.0


class H(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, fmt, *args):
        sys.stderr.write("%s %s\n" % (datetime.now(timezone.utc).strftime("%H:%M:%S.%f")[:-3], fmt % args))

    def send(self, status, body=b"", headers=None, ctype=None):
        self.send_response(status)
        for k, v in (headers or {}).items():
            self.send_header(k, v)
        if ctype:
            self.send_header("content-type", ctype)
        self.send_header("content-length", str(len(body)))
        self.end_headers()
        if self.command != "HEAD" and body:
            self.wfile.write(body)

    def err(self, code, status):
        self.send(status, ('<?xml version="1.0"?><Error><Code>%s</Code><Message>%s</Message></Error>' % (code, code)).encode(),
                  ctype="application/xml")

    def parts(self):
        u = urlparse(self.path)
        p = unquote(u.path)
        seg = p.split("/", 2)
        key = seg[2] if len(seg) > 2 and seg[2] else None
        return key, parse_qs(u.query, keep_blank_values=True)

    def body(self):
        n = int(self.headers.get("content-length") or 0)
        if self.headers.get("transfer-encoding", "").lower() == "chunked":
            out = b""
            while True:
                line = self.rfile.readline().strip()
                size = int(line.split(b";")[0], 16)
                if size == 0:
                    self.rfile.readline()
                    break
                out += self.rfile.read(size)
                self.rfile.readline()
            return out
        return self.rfile.read(n) if n else b""

    def do_HEAD(self):
        key, _ = self.parts()
        if key is None:
            return self.send(200)
        with LOCK:
            cur = OBJECTS.get(key)
        if not cur:
            return self.send(404)
        self.send_response(200)
        self.send_header("content-length", str(len(cur["body"])))
        self.send_header("etag", '"%s"' % cur["etag"])
        self.send_header("last-modified", formatdate(cur["t"], usegmt=True))
        self.end_headers()

    def do_GET(self):
        key, q = self.parts()
        if "list-type" in q:
            return self.list(q)
        if key is None:
            return self.send(200)
        with LOCK:
            cur = OBJECTS.get(key)
        if not cur:
            return self.err("NoSuchKey", 404)
        self.send(200, cur["body"], {"etag": '"%s"' % cur["etag"],
                                     "last-modified": formatdate(cur["t"], usegmt=True)})

    def list(self, q):
        prefix = (q.get("prefix") or [""])[0]
        after = (q.get("continuation-token") or [""])[0] or (q.get("start-after") or [""])[0]
        maxk = int((q.get("max-keys") or ["1000"])[0])
        delim = (q.get("delimiter") or [None])[0]
        with LOCK:
            snap = dict(OBJECTS)
        if delim:
            items = {}
            for k in snap:
                if not k.startswith(prefix):
                    continue
                at = k.find(delim, len(prefix))
                items[k[:at + len(delim)] if at >= 0 else k] = "dir" if at >= 0 else "key"
            ordered = sorted(k for k in items if k > after and not (after.endswith(delim) and k.startswith(after)))
            page = ordered[:maxk]
            body = "".join("<CommonPrefixes><Prefix>%s</Prefix></CommonPrefixes>" % esc(k) if items[k] == "dir" else
                           "<Contents><Key>%s</Key><Size>%d</Size><ETag>&quot;%s&quot;</ETag></Contents>"
                           % (esc(k), len(snap[k]["body"]), snap[k]["etag"]) for k in page)
            trunc = len(ordered) > len(page)
        else:
            ordered = sorted(k for k in snap if k.startswith(prefix) and k > after)
            page = ordered[:maxk]
            trunc = len(ordered) > len(page)
            body = "".join("<Contents><Key>%s</Key><Size>%d</Size><ETag>&quot;%s&quot;</ETag><LastModified>%s</LastModified></Contents>"
                           % (esc(k), len(snap[k]["body"]), snap[k]["etag"],
                              datetime.fromtimestamp(snap[k]["t"], timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z"))
                           for k in page)
        nxt = "<NextContinuationToken>%s</NextContinuationToken>" % esc(page[-1]) if trunc else ""
        xml = ('<?xml version="1.0"?><ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Name>b</Name>'
               "<Prefix>%s</Prefix><KeyCount>%d</KeyCount><MaxKeys>%d</MaxKeys><IsTruncated>%s</IsTruncated>%s%s</ListBucketResult>"
               % (esc(prefix), len(page), maxk, "true" if trunc else "false", body, nxt))
        self.send(200, xml.encode(), ctype="application/xml")

    def do_PUT(self):
        key, _ = self.parts()
        d = put_delay()
        if d > 0 and key is not None:
            # held before the body is read, as the extension's emulator does
            # (holdPut): a request the client gave up on commits nothing
            sys.stderr.write("%s delaying PUT %s by %.1f s\n" % (datetime.now(timezone.utc).strftime("%H:%M:%S.%f")[:-3], key, d))
            time.sleep(d)
            try:
                want = int(self.headers.get("content-length") or 0)
                data = self.body()
            except (OSError, ValueError):
                data, want = None, -1
            if data is None or len(data) != want:
                sys.stderr.write("%s PUT %s abandoned by the client: not committed\n" % (datetime.now(timezone.utc).strftime("%H:%M:%S.%f")[:-3], key))
                self.close_connection = True
                return
            import select
            r, _, _ = select.select([self.connection], [], [], 0)
            if r and not self.connection.recv(1, __import__("socket").MSG_PEEK):
                sys.stderr.write("%s PUT %s: client closed during the hold: not committed\n" % (datetime.now(timezone.utc).strftime("%H:%M:%S.%f")[:-3], key))
                self.close_connection = True
                return
        else:
            data = self.body()
        if key is None:
            return self.send(200)
        src = self.headers.get("x-amz-copy-source")
        with LOCK:
            cur = OBJECTS.get(key)
            if src is not None:
                sk = unquote(src).lstrip("/").split("/", 1)[1]
                s = OBJECTS.get(sk)
                if not s:
                    return self.err("NoSuchKey", 404)
                etag = uuid.uuid4().hex
                OBJECTS[key] = {"body": s["body"], "etag": etag, "t": time.time()}
                xml = ('<?xml version="1.0"?><CopyObjectResult><ETag>&quot;%s&quot;</ETag><LastModified>%s</LastModified></CopyObjectResult>'
                       % (etag, datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")))
                return self.send(200, xml.encode(), ctype="application/xml")
            im, inm = self.headers.get("if-match"), self.headers.get("if-none-match")
            ok = True
            if inm == "*" and cur:
                ok = False
            elif im is not None:
                if im == "*":
                    ok = cur is not None
                else:
                    ok = cur is not None and im.strip('"') == cur["etag"]
            if not ok:
                return self.err("PreconditionFailed", 412)
            etag = uuid.uuid4().hex
            OBJECTS[key] = {"body": data, "etag": etag, "t": time.time()}
        self.send(200, headers={"etag": '"%s"' % etag})

    def do_DELETE(self):
        key, _ = self.parts()
        with LOCK:
            OBJECTS.pop(key, None)
        self.send(204)

    def do_POST(self):
        self.body()
        self.err("NotImplemented", 501)


if __name__ == "__main__":
    ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
02Bog Flow
✓OPEN✓TRIAGED✓IN PROGRESS✓SHIPPED+ 1 MOREASSIGNED+ 8 MOREREVIEW+ 20 MOREPR_LINKEDPR_MERGED

Shipped

10/26/2026, 5:15:59 PM

Click a lifecycle step above to view its details.

03Sludge Pulse
zack assigned zack10/26/2026, 1:16:30 PM
Editable. Press Enter to edit.

vcjdeboer commented 10/28/2026, 12:36:57 PM

Follow-up after moving to 20261027.021509.0-sha.f96841b5.

Setup: one swamp serve (systemd, linux/aarch64), datastore format 2 (synced) on S3 via @swamp/s3-datastore 2026.10.01.1, no namespace, remote-only with one remote worker, default 30 s drain, log level info. The bucket has versioning on.

What we did: started a workflow run (its steps execute on the remote worker), then systemctl restart of the serve unit (SIGTERM) while the run was in flight.

Old serve's journal (UTC, trimmed):

08:46:43  Preparing push (uploading files)...
08:46:45  Committing index update...
08:46:46  Committed 67 file(s) to datastore index
08:47:03  (systemd) Stopping <serve unit>...
08:47:03  Shutting down, draining in-flight runs for up to 30s...
08:47:03  Draining 1 active run(s)...
08:47:19  Preparing push (uploading files)...
08:47:21  Committing index update...
08:47:21  Committed 37 file(s) to datastore index
08:47:33  Aborting 1 undrained run(s)...
08:47:45  Interrupted workflow run "<run id>" (server shutdown)
08:47:45  Preparing push (uploading files)...
08:47:46  Failed to record disconnect for "<worker>": "database is not open"
08:47:46  (systemd) <serve unit>: Deactivated successfully.

There is no Failed to push interrupted workflow run(s) ... line. The push that starts at 08:47:45 is the only one in this window that is not followed by Committing index update... / Committed N file(s).

New serve's journal: Hydrating local cache from remote datastore, Pulled 2 file(s), Boot: reaping stale runs via tracker, Boot: reconciling workflow run state, Boot: sweeping stale records; no Boot: pushed ... or Boot: settled ... line, and no skip or reap line for the run.

Datastore: after the restart the run read as running through serve until we cancelled it (admin workflow cancel, about 6 min later). The run's object in the bucket has exactly two versions: one status: running written 08:46:08, and one status: cancelled written by our cancel. No version with status: interrupted exists.

Questions:

  1. Is this a case the fix is meant to cover? From the outside it looks like the interrupted status did not reach the datastore while no push failure was reported, so the unpushed-interrupts path did not engage.
  2. Does the fix depend on a newer @swamp/s3-datastore than 2026.10.01.1?
  3. Would a run with --log-level debug on serve help? We can repeat the restart and send the relevant lines.

vcjdeboer commented 10/29/2026, 6:31:52 AM

@zack a short follow-up, since this issue is marked shipped and our ripple of 2026-10-28 (above) may not have reached you.

Where we stand: on 20261027.021509.0-sha.f96841b5 a run interrupted by a clean systemctl restart of serve still stays running in the S3 datastore. The shutdown push starts but never commits, no push failure is logged, so the unpushed-interrupts path never engages, and only an admin workflow cancel settles the run. Journal, boot lines and bucket versions are in the ripple above.

New since that ripple: we moved @swamp/s3-datastore from 2026.10.01.1 to 2026.10.24.2 and repeated the restart. Same result: the push reports no failure and the datastore keeps running. So our question 2 is answered from our side: the newer datastore extension does not change it.

Could you look at questions 1 and 3 in that ripple? We can repeat the restart with --log-level debug on serve and send the relevant [s3-sync] lines if that helps you narrow it down. If it is easier to track, feel free to reopen this one or we open a new issue for the remaining case.

Related, same setup: #3361 (an S3-backed serve invalidates the whole data catalog on every poll that pulls a file; the next query re-reads every version). It is still open and unassigned, and we added numbers on 2026-10-27. It is the bigger cost for us day to day, so if someone is on the S3 sync path for this fix anyway, that one is worth a look in the same pass.

Sign in to post a ripple.