Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(maintenance): add resumable internal backfill API (MUL-7365) (#8436)

Jiayuan Zhang02a8ff3e95ed
diff --git a/.env.example b/.env.example
index 72dfd5d989..68b891fe23 100644
--- a/.env.example
+++ b/.env.example
@@ -66,6 +66,9 @@ FRONTEND_ORIGIN=http://localhost:${FRONTEND_PORT}
# proxy auth. Do not expose this endpoint through the public app/API ingress.
# HTTP request metrics start accumulating only when this listener is enabled.
# METRICS_ADDR=127.0.0.1:9090
+# Optional container-loopback maintenance API. Use /app/maintenance via container exec.
+# Never publish this port. See docs/maintenance-jobs.md. Empty disables it.
+MAINTENANCE_PORT=
# REQUIRED. Signing key for auth JWTs, daemon JWTs, and avatar/attachment
# URL capability HMACs. Generate a strong random value:
# macOS/Linux: openssl rand -hex 32
diff --git a/Dockerfile b/Dockerfile
index 1a006ed3ac..8b0335a26f 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -19,6 +19,7 @@ ARG DATE=unknown
RUN cd server && CGO_ENABLED=0 go build -ldflags "-s -w -X main.version=${VERSION} -X main.commit=${COMMIT}" -o bin/server ./cmd/server
RUN cd server && CGO_ENABLED=0 go build -ldflags "-s -w -X main.version=${VERSION} -X main.commit=${COMMIT} -X main.date=${DATE}" -o bin/multica ./cmd/multica
RUN cd server && CGO_ENABLED=0 go build -ldflags "-s -w" -o bin/migrate ./cmd/migrate
+RUN cd server && CGO_ENABLED=0 go build -ldflags "-s -w" -o bin/maintenance ./cmd/maintenance
RUN cd server && CGO_ENABLED=0 go build -ldflags "-s -w" -o bin/backfill_task_usage_hourly ./cmd/backfill_task_usage_hourly
RUN cd server && CGO_ENABLED=0 go build -ldflags "-s -w" -o bin/backfill_codex_usage_cache ./cmd/backfill_codex_usage_cache
@@ -32,6 +33,7 @@ WORKDIR /app
COPY --from=builder /src/server/bin/server .
COPY --from=builder /src/server/bin/multica .
COPY --from=builder /src/server/bin/migrate .
+COPY --from=builder /src/server/bin/maintenance .
COPY --from=builder /src/server/bin/backfill_task_usage_hourly .
COPY --from=builder /src/server/bin/backfill_codex_usage_cache .
COPY server/migrations/ ./migrations/
diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yaml
index 1b67e24300..a37a49c63a 100644
--- a/deploy/helm/multica/templates/configmap.yaml
+++ b/deploy/helm/multica/templates/configmap.yaml
@@ -7,6 +7,7 @@ metadata:
data:
# --- Backend ---
PORT: "8080"
+ MAINTENANCE_PORT: {{ .Values.backend.config.maintenancePort | quote }}
MULTICA_DATABASE_STARTUP_TIMEOUT: {{ .Values.backend.config.databaseStartupTimeout | quote }}
MULTICA_DATABASE_CONNECT_TIMEOUT: {{ .Values.backend.config.databaseConnectTimeout | quote }}
DATABASE_SEARCH_WORK_MEM_MB: {{ .Values.backend.config.databaseSearchWorkMemMB | quote }}
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index b18a1cb22f..a44fc560fc 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -110,6 +110,8 @@ backend:
- ReadWriteOnce
# All non-secret backend env. Secret values come from `existingSecret`.
config:
+ # Optional container-loopback maintenance API; empty disables it. Never expose via Service/Ingress.
+ maintenancePort: ""
# The migrator and API server retry transient PostgreSQL startup failures
# within this budget. Set to 0 to restore fail-fast startup behavior.
databaseStartupTimeout: 3m
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 8c2e7e20f2..e4684630dc 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -70,6 +70,7 @@ services:
REDIS_URL: ${REDIS_URL:-}
REDIS_CLUSTER_MODE: ${REDIS_CLUSTER_MODE:-false}
PORT: "8080"
+ MAINTENANCE_PORT: ${MAINTENANCE_PORT:-}
METRICS_ADDR: ${METRICS_ADDR:-}
JWT_SECRET: ${JWT_SECRET:?JWT_SECRET must be set to a strong random value — generate one with 'openssl rand -hex 32'}
FRONTEND_ORIGIN: ${FRONTEND_ORIGIN:-http://localhost:3000}
diff --git a/docs/issue-status-lifecycle-rollout.md b/docs/issue-status-lifecycle-rollout.md
index 261504b7f3..8e003485e5 100644
--- a/docs/issue-status-lifecycle-rollout.md
+++ b/docs/issue-status-lifecycle-rollout.md
@@ -99,9 +99,11 @@ Release sequence:
custom-status automation inheritance; upgrading the daemon is required to
replace those instructions. Do not automatically restart or replay tasks.
-**Phase 2 is a separate PR/job, not implemented by phase 1.** It must batch by
-an indexed stable key, commit each batch, support dry-run/progress/retry/pause,
-and include system, custom and archived catalog rows. Before starting, prove
+**Phase 2 is an explicitly driven internal API**, documented in
+[the maintenance jobs runbook](maintenance-jobs.md). It uses a shared
+maintenance_job record, one indexed ID page per request, and atomic
+data/checkpoint commits. It supports dry-run/progress/retry/pause and includes
+system, custom and archived catalog rows. Before starting, prove
all writers use the new format and the compatible backend is fully deployed.
Set workload limits from the environment's API latency, lock wait, I/O, WAL and
replication budgets. Pausing the job must leave normal reads/writes working.
diff --git a/docs/maintenance-jobs.md b/docs/maintenance-jobs.md
new file mode 100644
index 0000000000..f448db4137
--- /dev/null
+++ b/docs/maintenance-jobs.md
@@ -0,0 +1,230 @@
+# Operator-driven maintenance jobs
+
+Maintenance runs through a separate HTTP listener in the API container. There
+is no startup backfill, scheduler, background executor, or automatic restart.
+The initial registered processor is `issue_status_category`, version 1. The
+shared `maintenance_job` table also supports later database repair/backfill
+processors with their own parameter, checkpoint and result schemas.
+
+## Enable the local entrypoint
+
+Set `MAINTENANCE_PORT` to an unused port (for example 6061) when deploying the
+API. Unset means disabled. The bind address is always **127.0.0.1** and cannot
+be overridden. Invalid configuration or a bind failure disables only this
+listener and logs an error; check the listener before attempting maintenance.
+
+Do not publish this port, add it to a Service/Ingress, or proxy these routes.
+There is deliberately no application authentication. Access relies on container
+exec/operational permissions and network-namespace isolation; another process
+in the same namespace can also connect. Host-networked containers share the
+host loopback namespace. This API is never mounted on the public router.
+Avoid placing credentials or user content in job parameters or logs.
+
+The backend image includes `/app/maintenance`, a standalone Go HTTP client.
+It needs no Python, curl, source checkout, or database credentials. It only
+connects to loopback, ignores HTTP proxy variables, and refuses redirects.
+Merely enabling the listener does not create or advance a job.
+No production execution is part of submitting this PR.
+
+Enable the listener using the deployment's existing configuration/release flow:
+
+- Helm: set `backend.config.maintenancePort: "6061"` in the release values.
+ The ConfigMap supplies `MAINTENANCE_PORT`; its checksum rolls the backend.
+ Neither the Service nor the container's published ports gains a maintenance port.
+- Compose: set `MAINTENANCE_PORT=6061` in the deployment `.env`, then recreate
+ the backend with `docker compose -f docker-compose.selfhost.yml up -d backend`.
+ The maintenance port is not published to the host.
+
+Run every command below in the **target backend container**. For example:
+
+```bash
+# Compose; omit -T only when an interactive terminal is desired.
+docker compose -f docker-compose.selfhost.yml exec -T backend /app/maintenance status --job JOB_UUID
+# Kubernetes; select a backend pod from the intended release/namespace.
+kubectl exec -n NAMESPACE POD -c backend -- /app/maintenance status --job JOB_UUID
+```
+
+Both forms inherit `MAINTENANCE_PORT` from the container. `--port 6061` can
+explicitly select another configured loopback port. Use `create --help` or
+`run --help` to check that the deployed image includes the command. A successful
+`status` or `create` request confirms the listener is reachable; a connection
+error means configuration/listener startup must be checked before continuing.
+No public API token or kubectl port-forward is required. Container exec is a
+privileged operational capability. Keep the attached exec session open until
+the command returns; this is not a background service.
+
+## Category backfill prerequisites
+
+1. Deploy PR1's matching migration runner through 478. Inspect the actual CHECKs
+ and functions, not just the migration ledger. Never execute historical 469
+ directly. The API checks the ledger, compatibility vocabulary, mapping
+ function, terminal spellings and its maintenance indexes.
+2. Finish the full compatible backend rollout, including every writer. Capture
+ deployment revision/replica evidence: the database cannot prove this.
+ `parameters.writers_upgraded=true` is the operator's explicit attestation,
+ not automatic proof of deployment.
+3. Apply migrations 485–488. They only create the maintenance table and three
+ unique indexes; indexes run concurrently in separate migration files with
+ invalid-index cleanup hooks. No issue-status rows are changed.
+4. Record baseline API latency/error rate, row-lock waits, DB I/O, WAL rate and
+ replica lag. Choose batch/delay limits against the environment's existing
+ alert budgets, beginning with a bounded canary. Pause if any metric exceeds
+ its agreed budget; reduce batch size/increase delay before resuming.
+ No fixed throughput or historical row count is a current safety guarantee.
+
+## Dry-run, then apply
+
+The driver requires explicit batch size, delay and both SQL timeouts for
+**create and configure**, including dry-runs. The following values are an
+example for a monitored canary, not production defaults or a throughput promise.
+Select them against the target database's latency/lock/replica-lag budgets.
+Commands are shown without the container-exec prefix for readability:
+
+```bash
+/app/maintenance create --idempotency-key status-category-v1-check-001 \
+ --batch-size 500 --delay-ms 100 --lock-timeout-ms 500 --statement-timeout-ms 3000
+```
+
+Keep the returned `id`. Creation defaults to dry-run; dry-run persists its
+progress/report but never changes category data. One command can drive the
+whole survey, with each HTTP request still advancing only one short transaction:
+
+```bash
+# Canary: exits 2 (incomplete) unless this one batch completes the job.
+/app/maintenance run --job JOB_UUID --max-batches 1 --max-seconds 30
+# After checking canary metrics, run a bounded window automatically.
+/app/maintenance run --job JOB_UUID --max-batches 3000 --max-seconds 1800
+/app/maintenance status --job JOB_UUID
+```
+
+For 600,000 rows at batch size 500, a dry-run needs about 1,201 advances;
+apply plus verification needs about 2,402, including end-of-pass detection.
+The 3,000-batch/1,800-second example has headroom for that row count but is
+still a hard stop. At a 100ms batch delay, waiting alone is about 240 seconds
+for apply plus verification, before database and HTTP time. A smaller batch,
+more rows, contention, or retries can exceed either budget. Re-run `status`,
+inspect metrics, and explicitly start another bounded `run` if incomplete.
+No one needs to invoke thousands of curl commands manually.
+
+`run` writes the observed job JSON after each advance and exits:
+
+- **0:** the persisted job is `completed` (for dry-run, only the survey completed).
+- **2:** incomplete because either batch or elapsed-time budget ran out.
+- **1:** invalid arguments, cancellation, a paused/cancelled job, or an API error.
+
+Time includes requests, delay and retries; sleeps and requests are cancellable.
+A timeout or transport error can leave a final commit's acknowledgement unknown.
+Read `status` before continuing; do not interpret incomplete/error as rollback.
+Keep stdout and stderr in the operator session log. Process exit never restarts
+itself or schedules later work.
+
+Once dry-run is completed, create a **new** apply record with a new key:
+
+```bash
+/app/maintenance create --idempotency-key status-category-v1-apply-001 \
+ --apply --parameters '{"writers_upgraded":true}' \
+ --batch-size 500 --delay-ms 100 --lock-timeout-ms 500 --statement-timeout-ms 3000
+```
+
+Use the batch/delay/timeouts selected from the dry-run and monitored apply
+canary. Run one batch first, check the metrics, then continue with an explicit
+budget as above. Dry-run cannot measure update WAL/lock impact; the apply
+canary is required too. Tuning a paused record preserves the cursor.
+
+Creating with the same idempotency key and identical normalized parameters
+returns the original job. Reusing that key with different input conflicts.
+Only one ready/paused record per job type and scope is permitted, including
+dry-runs. Finish or explicitly cancel the existing record before starting
+another. Different logical scopes must be disjoint; new processors that allow
+overlapping scopes must implement an additional conflict guard.
+
+## Pause, tune, resume, failures
+
+Stopping calls stops progress. Query `status`, then use its revision for an
+intentional mutation. These operations may return busy while a short batch
+holds the job row; query/retry after it finishes. A stale revision performs no
+work. Each successful mutation returns the new revision:
+
+```bash
+/app/maintenance pause --job JOB_UUID --revision CURRENT_REVISION
+/app/maintenance configure --job JOB_UUID --revision PAUSED_REVISION \
+ --batch-size 100 --delay-ms 1000 --lock-timeout-ms 250 --statement-timeout-ms 2000
+/app/maintenance resume --job JOB_UUID --revision CONFIGURED_REVISION
+/app/maintenance run --job JOB_UUID --max-batches 3000 --max-seconds 1800
+# To stop permanently, using the latest revision:
+/app/maintenance cancel --job JOB_UUID --revision CURRENT_REVISION
+```
+
+Cancellation preserves already committed data and the global audit record;
+it does not reverse a backfill. Configuration replaces operational limits,
+preserving checkpoint and immutable parameters. Limits: batch 1–5000,
+delay 1–60000ms, and 1 <= lock timeout <= statement timeout <= 5000ms.
+Increasing/decreasing limits cannot erase an existing delay. The raw HTTP API
+retains default normalization for omitted/zero limits; operational runs should
+use the packaged driver, which requires explicit values.
+
+The underlying routes remain `POST /maintenance/jobs`,
+`GET /maintenance/jobs/{id}`, and `POST /maintenance/jobs/{id}/{action}`.
+Mutations carry `{"revision":N}`; configure also carries `options`.
+The driver retries an ambiguous advance using its **original** revision.
+409 with a changed revision acknowledges current state without advancing again;
+429 respects the database delay; 409 without a job retries busy with backoff.
+
+Each batch locks the maintenance row NOWAIT, scans an indexed ID page, updates
+only still-legacy categories from their current values, and commits data,
+checkpoint, counters and revision in one transaction. It includes system,
+custom and archived rows, preserving all fields except category. No issue
+update events or agent runs are emitted. It does not use SKIP LOCKED or OFFSET.
+
+On SQL failure the batch savepoint rolls back all data changes. The outer
+transaction records a paused state and error without advancing the checkpoint.
+Timeout/deadlock/serialization errors are marked retryable; the driver retries
+with capped exponential backoff (default 3, configurable up to 10), using the
+new revision to resume that failed batch. Other errors stop the driver.
+A previously paused job is not automatically resumed without `--resume`.
+There is no automatic retry after process exit. The driver has batch and wall
+time budgets; Ctrl-C stops driving requests.
+
+If the connection/container disappears before commit, data and progress both
+roll back. If it disappears after commit, another replica can resume from the
+stored cursor. If cancellation prevents even the error record from committing,
+the checkpoint stays unchanged and server logs/client transport error provide
+the failure evidence; inspect GET before retrying. Graceful shutdown drains
+the internal listener before closing the database pool.
+
+## Completion and evidence
+
+Application runs move from the scan phase into a fresh, independently paged
+verification phase. Verification rejects residual legacy values, unknown
+categories and noncanonical system pairs. A bad page pauses with the first
+offending status ID. Fix the cause, then resume; for residuals behind the scan
+cursor, cancel and start a new pass after eliminating old writers.
+
+Only a complete verification pass produces `status=completed` and
+`result.remaining_legacy=0`. That report depends on the no-old-writers rollout
+precondition; a paged scan cannot certify that an old writer will never write
+again. Dry-run completion only means the read-only survey completed, not that
+the data has been converted. Dry-run counts and `would_update` are observations
+during a paged scan, not a globally consistent snapshot. Progress is cumulative;
+`updated` counts actual committed updates, while `would_update` counts old
+values observed before any concurrent application normalization. Neither is a
+live remaining-row count. Use a fresh dry-run to refresh backlog evidence.
+
+Save the job JSON, deployment evidence, monitoring/canary results and operator
+session log. Completed/cancelled rows are retained; repeated maintenance creates
+new records rather than resetting history. Down migrations intentionally retain
+state and indexes. Keep the compatible backend and fix forward on failures.
+
+PR3 remains separate: no strict CHECK, validation DDL, legacy-reader removal,
+or wire-protocol retirement is triggered by this job. Installed-client API
+compatibility remains after backfill completion.
+
+## Adding a processor
+
+Register a code-defined `maintenance.Processor` with a type and version. Validate
+scope and parameters, implement preflight and one bounded Step, and return
+versioned checkpoint/progress/result JSON objects plus a completion flag.
+A processor uses only the supplied primary-database transaction. Unknown
+types/versions and malformed state fail closed. This is not an arbitrary SQL
+execution endpoint. Checkpoint atomicity does not cover external side effects;
+such processors need their own idempotency/recovery design before registration.
diff --git a/scripts/helm-config.test.sh b/scripts/helm-config.test.sh
index 5e2b48a44b..39ac46d09f 100644
--- a/scripts/helm-config.test.sh
+++ b/scripts/helm-config.test.sh
@@ -37,6 +37,13 @@ require_rendered_value "$default_config" 'MULTICA_CLOUD_URL: ""'
require_rendered_value "$default_config" 'MULTICA_DATABASE_STARTUP_TIMEOUT: "3m"'
require_rendered_value "$default_config" 'MULTICA_DATABASE_CONNECT_TIMEOUT: "5s"'
+require_rendered_value "$default_config" 'MAINTENANCE_PORT: ""'
+maintenance_config="$(helm template multica "$CHART_DIR" --show-only templates/configmap.yaml --set-string backend.config.maintenancePort=6061)"
+require_rendered_value "$maintenance_config" 'MAINTENANCE_PORT: "6061"'
+maintenance_backend="$(helm template multica "$CHART_DIR" --show-only templates/backend.yaml --set-string backend.config.maintenancePort=6061)"
+reject_rendered_value "$maintenance_backend" 'containerPort: 6061'
+reject_rendered_value "$maintenance_backend" 'port: 6061'
+
default_backend="$(
helm template multica "$CHART_DIR" \
--show-only templates/backend.yaml
diff --git a/scripts/selfhost-config.test.sh b/scripts/selfhost-config.test.sh
index 2c11ed2ac3..d8d7051080 100755
--- a/scripts/selfhost-config.test.sh
+++ b/scripts/selfhost-config.test.sh
@@ -59,6 +59,13 @@ require_config "$config" 'MULTICA_APP_URL: http://localhost:3100'
require_config "$config" 'SMTP_FROM_EMAIL: [email protected]'
require_config "$config" 'MULTICA_DATABASE_STARTUP_TIMEOUT: 3m'
require_config "$config" 'MULTICA_DATABASE_CONNECT_TIMEOUT: 5s'
+require_config "$config" 'MAINTENANCE_PORT: ""'
+maintenance_config="$(MAINTENANCE_PORT=6061 docker compose --env-file "$tmp_env" -f docker-compose.selfhost.yml config)"
+require_config "$maintenance_config" 'MAINTENANCE_PORT: "6061"'
+if grep -Eq '(published|target):.*6061' <<<"$maintenance_config"; then
+ echo "Maintenance loopback port must not be published"
+ exit 1
+fi
require_config "$config" 'DATABASE_REPLICA_URL: postgres://reader:[email protected]:5432/multica?sslmode=require'
require_config "$config" 'DATABASE_REPLICA_MAX_CONNS: "12"'
require_config "$config" 'DATABASE_REPLICA_MIN_CONNS: "1"'
diff --git a/server/cmd/maintenance/main.go b/server/cmd/maintenance/main.go
new file mode 100644
index 0000000000..c001e52903
--- /dev/null
+++ b/server/cmd/maintenance/main.go
@@ -0,0 +1,294 @@
+// maintenance drives the container-local API; it never connects to the database.
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "os/signal"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/maintenance"
+)
+
+var errIncomplete = errors.New("incomplete: run budget exhausted; inspect the persisted job before continuing")
+
+type response struct {
+ Job *maintenance.Job `json:"job,omitempty"`
+ Error string `json:"error,omitempty"`
+ Retryable bool `json:"retryable,omitempty"`
+}
+
+type client struct {
+ base string
+ http *http.Client
+ out io.Writer
+}
+
+func (c client) call(ctx context.Context, path string, body any) (int, response, error) {
+ method := http.MethodGet
+ var data []byte
+ if body != nil {
+ method = http.MethodPost
+ var err error
+ data, err = json.Marshal(body)
+ if err != nil {
+ return 0, response{}, err
+ }
+ }
+ req, err := http.NewRequestWithContext(ctx, method, c.base+path, bytes.NewReader(data))
+ if err != nil {
+ return 0, response{}, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ res, err := c.http.Do(req)
+ if err != nil {
+ return 0, response{}, err
+ }
+ defer res.Body.Close()
+ var payload response
+ if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&payload); err != nil {
+ return res.StatusCode, payload, err
+ }
+ if res.StatusCode == 200 && (payload.Job == nil || payload.Job.ID == "") {
+ return res.StatusCode, payload, errors.New("missing job in API response")
+ }
+ return res.StatusCode, payload, nil
+}
+
+func (c client) once(ctx context.Context, path string, body any) (*maintenance.Job, error) {
+ code, p, err := c.call(ctx, path, body)
+ if err != nil {
+ return nil, err
+ }
+ if code != 200 {
+ return nil, fmt.Errorf("HTTP %d: %s", code, p.Error)
+ }
+ return p.Job, nil
+}
+
+func sleep(ctx context.Context, delay time.Duration) error {
+ t := time.NewTimer(max(0, delay))
+ defer t.Stop()
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-t.C:
+ return nil
+ }
+}
+
+// advance retries the original revision on ambiguous transport failures. A
+// stale revision acknowledges a committed batch without doing another one.
+func (c client) advance(ctx context.Context, path string, job *maintenance.Job, retries int) (*maintenance.Job, error) {
+ revision := job.Revision
+ for attempt := 0; ; attempt++ {
+ code, p, err := c.call(ctx, path+"/advance", map[string]any{"revision": revision})
+ if err == nil {
+ if code == 200 || (code == 409 && p.Job != nil && p.Job.Revision != revision) {
+ return p.Job, nil
+ }
+ if !p.Retryable {
+ return nil, fmt.Errorf("HTTP %d: %s", code, p.Error)
+ }
+ err = fmt.Errorf("HTTP %d: %s", code, p.Error)
+ }
+ if attempt >= retries {
+ return nil, err
+ }
+ if err := sleep(ctx, min(250*time.Millisecond*time.Duration(1<<attempt), 5*time.Second)); err != nil {
+ return nil, err
+ }
+ if p.Retryable && p.Job != nil && p.Job.Status == "paused" {
+ // Only resume a retryable failure returned by this invocation, never
+ // a pre-existing/operator pause. A lost resume response stops safely.
+ resumed, err := c.once(ctx, path+"/resume", map[string]any{"revision": p.Job.Revision})
+ if err != nil {
+ return nil, err
+ }
+ revision = resumed.Revision
+ }
+ }
+}
+
+func (c client) drive(ctx context.Context, path string, batches, retries int, resume bool) error {
+ job, err := c.once(ctx, path, nil)
+ if err != nil {
+ return err
+ }
+ if resume && job.Status == "paused" {
+ job, err = c.once(ctx, path+"/resume", map[string]any{"revision": job.Revision})
+ if err != nil {
+ return err
+ }
+ }
+ for batch := 0; ; batch++ {
+ if err := json.NewEncoder(c.out).Encode(job); err != nil {
+ return err
+ }
+ if job.Status == "completed" {
+ return nil
+ }
+ if job.Status != "ready" {
+ return fmt.Errorf("job is %s: %s; inspect before resuming", job.Status, job.LastError)
+ }
+ if batch == batches {
+ return errIncomplete
+ }
+ if err := sleep(ctx, time.Until(job.NextAllowedAt)); err != nil {
+ return err
+ }
+ job, err = c.advance(ctx, path, job, retries)
+ if err != nil {
+ return err
+ }
+ }
+}
+
+func run(ctx context.Context, args []string, envPort string, out, stderr io.Writer) error {
+ if len(args) == 0 {
+ return errors.New("usage: maintenance {create|status|run|pause|resume|cancel|configure} [flags]; use COMMAND --help")
+ }
+ action := args[0]
+ f := flag.NewFlagSet("maintenance "+action, flag.ContinueOnError)
+ f.SetOutput(stderr)
+ port := f.String("port", envPort, "loopback API port (default MAINTENANCE_PORT)")
+ jobID := f.String("job", "", "persisted job UUID")
+ revision := f.Int64("revision", -1, "expected revision for pause/resume/cancel/configure")
+ maxBatches := f.Int("max-batches", 0, "required run batch budget; unfinished exits 2")
+ maxSeconds := f.Int("max-seconds", 0, "required run wall-clock budget including requests/retries")
+ retries := f.Int("max-retries", 3, "retries per advance (0..10)")
+ resume := f.Bool("resume", false, "explicitly resume an initially paused job before running")
+ jobType := f.String("type", "issue_status_category", "registered processor type")
+ version := f.Int("version", 1, "processor version")
+ scope := f.String("scope", "database", "processor scope")
+ key := f.String("idempotency-key", "", "stable unique creation key; reuse on an ambiguous create response")
+ apply := f.Bool("apply", false, "write data (default is dry-run)")
+ params := f.String("parameters", "{}", "processor parameters as a JSON object; apply category jobs require writers_upgraded=true")
+ var opts maintenance.Options
+ f.IntVar(&opts.BatchSize, "batch-size", 0, "required for create/configure: rows per transaction (1..5000)")
+ f.IntVar(&opts.DelayMS, "delay-ms", 0, "required for create/configure: delay between batches (1..60000)")
+ f.IntVar(&opts.LockTimeoutMS, "lock-timeout-ms", 0, "required for create/configure: lock timeout")
+ f.IntVar(&opts.StatementTimeoutMS, "statement-timeout-ms", 0, "required for create/configure: statement timeout (<=5000)")
+ if err := f.Parse(args[1:]); err != nil {
+ return err
+ }
+ if f.NArg() != 0 {
+ return errors.New("unexpected positional arguments")
+ }
+ // Reject tuning/creation flags on run rather than silently using the job's
+ // persisted limits when the operator expected a smaller batch or a dry-run.
+ allowed := map[string]string{
+ "create": "port type version scope idempotency-key apply parameters batch-size delay-ms lock-timeout-ms statement-timeout-ms",
+ "status": "port job",
+ "run": "port job max-batches max-seconds max-retries resume",
+ "pause": "port job revision", "resume": "port job revision", "cancel": "port job revision",
+ "configure": "port job revision batch-size delay-ms lock-timeout-ms statement-timeout-ms",
+ }
+ flags, ok := allowed[action]
+ if !ok {
+ return fmt.Errorf("unknown command %q", action)
+ }
+ var invalidFlag string
+ f.Visit(func(v *flag.Flag) {
+ if !strings.Contains(" "+flags+" ", " "+v.Name+" ") {
+ invalidFlag = v.Name
+ }
+ })
+ if invalidFlag != "" {
+ return fmt.Errorf("--%s is not supported by %s", invalidFlag, action)
+ }
+ p, err := strconv.Atoi(*port)
+ if err != nil || p < 1 || p > 65535 {
+ return errors.New("set --port or MAINTENANCE_PORT to 1..65535")
+ }
+ if action != "create" {
+ if _, err := uuid.Parse(*jobID); err != nil {
+ return errors.New("--job must be a UUID")
+ }
+ }
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.Proxy = nil // Loopback never uses an operator's proxy.
+ defer transport.CloseIdleConnections()
+ c := client{base: "http://127.0.0.1:" + strconv.Itoa(p), http: &http.Client{Transport: transport, Timeout: 20 * time.Second,
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, out: out}
+ path := "/maintenance/jobs/" + *jobID
+ if action == "run" {
+ if *maxBatches < 1 || *maxSeconds < 1 || *maxSeconds > 86400 || *retries < 0 || *retries > 10 {
+ return errors.New("run requires --max-batches >= 1 and --max-seconds 1..86400; --max-retries 0..10")
+ }
+ ctx, cancel := context.WithTimeout(ctx, time.Duration(*maxSeconds)*time.Second)
+ defer cancel()
+ err := c.drive(ctx, path, *maxBatches, *retries, *resume)
+ if err != nil && errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ return errIncomplete
+ }
+ return err
+ }
+ var body any
+ if action == "create" || action == "configure" {
+ if opts.BatchSize < 1 || opts.BatchSize > 5000 || opts.DelayMS < 1 || opts.DelayMS > 60000 || opts.LockTimeoutMS < 1 || opts.StatementTimeoutMS < opts.LockTimeoutMS || opts.StatementTimeoutMS > 5000 {
+ return errors.New("create/configure require explicit --batch-size, --delay-ms, --lock-timeout-ms, --statement-timeout-ms within documented limits; choose values using a monitored canary")
+ }
+ }
+ switch action {
+ case "create":
+ if *key == "" {
+ return errors.New("create requires --idempotency-key")
+ }
+ var object map[string]json.RawMessage
+ if err := json.Unmarshal([]byte(*params), &object); err != nil || object == nil {
+ return errors.New("--parameters must be a JSON object")
+ }
+ dry := !*apply
+ body = maintenance.CreateRequest{Type: *jobType, Version: *version, Scope: *scope, IdempotencyKey: *key, DryRun: &dry, Options: opts, Parameters: json.RawMessage(*params)}
+ path = "/maintenance/jobs"
+ case "status":
+ case "pause", "resume", "cancel", "configure":
+ if *revision < 0 {
+ return errors.New("mutation requires the current --revision; obtain it with status")
+ }
+ path += "/" + action
+ body = map[string]any{"revision": *revision}
+ if action == "configure" {
+ body = map[string]any{"revision": *revision, "options": opts}
+ }
+ default:
+ return fmt.Errorf("unknown command %q", action)
+ }
+ job, err := c.once(ctx, path, body)
+ if err != nil {
+ return err
+ }
+ return json.NewEncoder(out).Encode(job)
+}
+
+func exitCode(err error) int {
+ if err == nil || errors.Is(err, flag.ErrHelp) {
+ return 0
+ }
+ if errors.Is(err, errIncomplete) {
+ return 2
+ }
+ return 1
+}
+
+func main() {
+ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ err := run(ctx, os.Args[1:], os.Getenv("MAINTENANCE_PORT"), os.Stdout, os.Stderr)
+ cancel()
+ if err != nil && !errors.Is(err, flag.ErrHelp) {
+ fmt.Fprintln(os.Stderr, err)
+ }
+ os.Exit(exitCode(err))
+}
diff --git a/server/cmd/maintenance/main_test.go b/server/cmd/maintenance/main_test.go
new file mode 100644
index 0000000000..b0636ad528
--- /dev/null
+++ b/server/cmd/maintenance/main_test.go
@@ -0,0 +1,222 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/maintenance"
+)
+
+const testID = "00000000-0000-4000-8000-000000000001"
+
+func testJob(revision int64, status string) *maintenance.Job {
+ return &maintenance.Job{ID: testID, Revision: revision, Status: status, NextAllowedAt: time.Now().Add(-time.Second)}
+}
+
+func TestRunThousandsOfBatchesAndCompletion(t *testing.T) {
+ var advances int64
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "POST" {
+ var body struct{ Revision int64 }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ if body.Revision != advances {
+ t.Errorf("revision=%d advances=%d", body.Revision, advances)
+ }
+ advances++
+ }
+ status := "ready"
+ if advances == 2402 {
+ status = "completed"
+ }
+ _ = json.NewEncoder(w).Encode(response{Job: testJob(advances, status)})
+ }))
+ defer srv.Close()
+ u, _ := url.Parse(srv.URL)
+ var out bytes.Buffer
+ err := run(context.Background(), []string{"run", "--job", testID, "--max-batches", "3000", "--max-seconds", "30"}, u.Port(), &out, io.Discard)
+ if err != nil || advances != 2402 || exitCode(err) != 0 {
+ t.Fatalf("advances=%d err=%v", advances, err)
+ }
+ if !strings.Contains(out.String(), `"status":"completed"`) {
+ t.Fatal("missing completion report")
+ }
+}
+
+func TestRunBudgetsAreIncomplete(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ next time.Time
+ batches string
+ wantPosts int
+ }{
+ {"batch", time.Now().Add(-time.Hour), "1", 1},
+ {"time", time.Now().Add(time.Hour), "3000", 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ posts := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "POST" {
+ posts++
+ }
+ j := testJob(int64(posts), "ready")
+ j.NextAllowedAt = tc.next
+ _ = json.NewEncoder(w).Encode(response{Job: j})
+ }))
+ defer srv.Close()
+ u, _ := url.Parse(srv.URL)
+ err := run(context.Background(), []string{"run", "--job", testID, "--max-batches", tc.batches, "--max-seconds", "1"}, u.Port(), io.Discard, io.Discard)
+ if !errors.Is(err, errIncomplete) || exitCode(err) != 2 || posts != tc.wantPosts {
+ t.Fatalf("posts=%d err=%v", posts, err)
+ }
+ })
+ }
+}
+
+type roundTrip func(*http.Request) (*http.Response, error)
+
+func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func TestAdvanceRetriesOriginalRevisionAfterLostResponse(t *testing.T) {
+ var revisions []int64
+ c := client{base: "http://127.0.0.1", http: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
+ var body struct{ Revision int64 }
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ revisions = append(revisions, body.Revision)
+ if len(revisions) == 1 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ data, _ := json.Marshal(response{Job: testJob(8, "completed")})
+ return &http.Response{StatusCode: 409, Body: io.NopCloser(bytes.NewReader(data)), Header: make(http.Header)}, nil
+ })}}
+ j, err := c.advance(context.Background(), "/maintenance/jobs/"+testID, testJob(7, "ready"), 1)
+ if err != nil || j.Revision != 8 || !reflect.DeepEqual(revisions, []int64{7, 7}) {
+ t.Fatalf("revisions=%v job=%+v err=%v", revisions, j, err)
+ }
+}
+
+func TestRetryableFailureResumesButOperatorPauseStops(t *testing.T) {
+ var actions []string
+ var revisions []int64
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ actions = append(actions, r.URL.Path)
+ var body struct{ Revision int64 }
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ revisions = append(revisions, body.Revision)
+ switch len(actions) {
+ case 1:
+ w.WriteHeader(503)
+ _ = json.NewEncoder(w).Encode(response{Job: testJob(1, "paused"), Retryable: true})
+ case 2:
+ _ = json.NewEncoder(w).Encode(response{Job: testJob(2, "ready")})
+ case 3:
+ _ = json.NewEncoder(w).Encode(response{Job: testJob(3, "completed")})
+ default:
+ t.Error("unexpected retry")
+ }
+ }))
+ defer srv.Close()
+ c := client{base: srv.URL, http: srv.Client(), out: io.Discard}
+ j, err := c.advance(context.Background(), "/job", testJob(0, "ready"), 1)
+ if err != nil || j.Status != "completed" || !reflect.DeepEqual(actions, []string{"/job/advance", "/job/resume", "/job/advance"}) || !reflect.DeepEqual(revisions, []int64{0, 1, 2}) {
+ t.Fatalf("actions=%v revisions=%v err=%v", actions, revisions, err)
+ }
+
+ posts := 0
+ paused := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "POST" {
+ posts++
+ }
+ _ = json.NewEncoder(w).Encode(response{Job: testJob(1, "paused")})
+ }))
+ defer paused.Close()
+ c.base = paused.URL
+ if err := c.drive(context.Background(), "/job", 10, 3, false); err == nil || posts != 0 {
+ t.Fatalf("posts=%d err=%v", posts, err)
+ }
+}
+
+func TestRetryBudgetAndCancellation(t *testing.T) {
+ calls := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ w.WriteHeader(409)
+ _ = json.NewEncoder(w).Encode(response{Error: "busy", Retryable: true})
+ }))
+ defer srv.Close()
+ c := client{base: srv.URL, http: srv.Client()}
+ if _, err := c.advance(context.Background(), "/job", testJob(0, "ready"), 1); err == nil || calls != 2 {
+ t.Fatalf("calls=%d err=%v", calls, err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if err := sleep(ctx, time.Hour); !errors.Is(err, context.Canceled) {
+ t.Fatal(err)
+ }
+}
+
+func TestCommandsAndExplicitLimits(t *testing.T) {
+ var paths []string
+ var bodies []map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ paths = append(paths, r.Method+" "+r.URL.Path)
+ var body map[string]any
+ if r.Method == "POST" {
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ }
+ bodies = append(bodies, body)
+ _ = json.NewEncoder(w).Encode(response{Job: testJob(4, "paused")})
+ }))
+ defer srv.Close()
+ u, _ := url.Parse(srv.URL)
+ opts := []string{"--batch-size", "500", "--delay-ms", "100", "--lock-timeout-ms", "500", "--statement-timeout-ms", "3000"}
+ for _, cmd := range []string{"create", "status", "pause", "resume", "cancel", "configure"} {
+ args := []string{cmd}
+ if cmd != "create" {
+ args = append(args, "--job", testID)
+ }
+ if cmd != "create" && cmd != "status" {
+ args = append(args, "--revision", "3")
+ }
+ if cmd == "create" {
+ args = append(args, "--idempotency-key", "test", "--apply", "--parameters", `{"writers_upgraded":true}`)
+ }
+ if cmd == "create" || cmd == "configure" {
+ args = append(args, opts...)
+ }
+ if err := run(context.Background(), args, u.Port(), io.Discard, io.Discard); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if len(paths) != 6 || paths[0] != "POST /maintenance/jobs" || paths[1] != "GET /maintenance/jobs/"+testID || bodies[0]["dry_run"] != false || bodies[5]["revision"] != float64(3) {
+ t.Fatalf("paths=%v bodies=%v", paths, bodies)
+ }
+ for _, args := range [][]string{
+ {"create", "--idempotency-key", "bad", "--apply"},
+ {"configure", "--job", testID, "--revision", "3"},
+ {"run", "--job", testID},
+ {"run", "--job", testID, "--batch-size", "10", "--max-batches", "3000", "--max-seconds", "1"},
+ {"run", "--job", testID, "--max-batches", "3000", "--max-seconds", "0"},
+ {"cancel", "--job", testID},
+ {"status", "--job", "not-a-uuid"},
+ {"status", "--job", testID, "--port", "0.0.0.0:6061"},
+ } {
+ if err := run(context.Background(), args, u.Port(), io.Discard, io.Discard); err == nil {
+ t.Fatalf("accepted %v", args)
+ }
+ }
+ if len(paths) != 6 {
+ t.Fatal("invalid arguments reached API")
+ }
+}
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 84686d762f..7d7b2f1164 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,9 @@ var pgBigmOperatorClass = extensionOperatorClass{
// they are still pending: a fresh self-hosted install, which is exactly where an
// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "486_maintenance_job_id_index": "idx_maintenance_job_id",
+ "487_maintenance_job_idempotency_index": "idx_maintenance_job_idempotency",
+ "488_maintenance_job_active_index": "idx_maintenance_job_active",
"035_task_queue_issue_id_index": "idx_agent_task_queue_issue_id",
"067_task_queue_claim_candidate_index": "idx_agent_task_queue_claim_candidates",
"074_task_usage_updated_at_index": "idx_task_usage_updated_at",
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 387f207a22..5fa135c206 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -24,6 +24,7 @@ import (
"github.com/multica-ai/multica/server/internal/handler"
"github.com/multica-ai/multica/server/internal/integrations/wecom"
"github.com/multica-ai/multica/server/internal/logger"
+ "github.com/multica-ai/multica/server/internal/maintenance"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/profiling"
"github.com/multica-ai/multica/server/internal/realtime"
@@ -681,6 +682,10 @@ func main() {
srv := newMainHTTPServer(":"+port, r)
profilingServer := profiling.NewServer()
+ maintenanceServer, maintenanceErr := maintenance.NewServer(os.Getenv("MAINTENANCE_PORT"), maintenance.NewService(pool, maintenance.StatusCategory{}))
+ if maintenanceErr != nil {
+ slog.Error("maintenance listener disabled", "error", maintenanceErr)
+ }
// Start background workers.
sweepCtx, sweepCancel := context.WithCancel(context.Background())
@@ -813,6 +818,15 @@ func main() {
}()
}
+ if maintenanceServer != nil {
+ go func() {
+ slog.Info("maintenance server starting", "addr", maintenanceServer.Addr)
+ if err := maintenanceServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+ slog.Error("maintenance listener disabled", "error", err)
+ }
+ }()
+ }
+
go func() {
slog.Info("pprof server starting", "addr", profilingServer.Addr)
if err := profilingServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
@@ -846,6 +860,17 @@ func main() {
// finds no socket to deliver over.
shutdownSequence{
StopAutopilot: autopilotCancel,
+ DrainMaintenance: func() {
+ if maintenanceServer == nil {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 16*time.Second)
+ defer cancel()
+ if err := maintenanceServer.Shutdown(ctx); err != nil {
+ slog.Error("maintenance shutdown interrupted", "error", err)
+ _ = maintenanceServer.Close()
+ }
+ },
DrainHTTP: func() {
apiShutdownCtx, apiShutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
if err := srv.Shutdown(apiShutdownCtx); err != nil {
diff --git a/server/cmd/server/maintenance_test.go b/server/cmd/server/maintenance_test.go
new file mode 100644
index 0000000000..ae336d9ceb
--- /dev/null
+++ b/server/cmd/server/maintenance_test.go
@@ -0,0 +1,29 @@
+package main
+
+import (
+ "bytes"
+ "io"
+ "net/http"
+ "testing"
+)
+
+func TestMaintenanceRoutesAreAbsentFromPublicServer(t *testing.T) {
+ for _, path := range []string{"/maintenance/jobs", "/api/maintenance/jobs", "/maintenance/jobs/00000000-0000-0000-0000-000000000001/advance"} {
+ req, err := http.NewRequest("POST", testServer.URL+path, bytes.NewBufferString("{}"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Even an authenticated application user cannot invoke the internal API here.
+ req.Header.Set("Authorization", "Bearer "+testToken)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusNotFound {
+ t.Fatalf("%s: %d %s", path, resp.StatusCode, body)
+ }
+ }
+}
diff --git a/server/cmd/server/shutdown.go b/server/cmd/server/shutdown.go
index 711e2dd526..9bc51caccc 100644
--- a/server/cmd/server/shutdown.go
+++ b/server/cmd/server/shutdown.go
@@ -23,6 +23,9 @@ type shutdownSequence struct {
// StopAutopilot first: it schedules work the rest of the system performs.
StopAutopilot func()
+ // Drain the internal maintenance listener while the primary pool is alive.
+ DrainMaintenance func()
+
// DrainHTTP before anything that serves it. In-flight handlers finish
// calling Schedule() before the scheduler stops, and no new task
// completion can arrive after this — which is what makes the relay stop
@@ -61,6 +64,7 @@ type shutdownSequence struct {
func (s shutdownSequence) run() {
for _, step := range []func(){
s.StopAutopilot,
+ s.DrainMaintenance,
s.DrainHTTP,
s.StopOutboundRelay,
s.CancelWorkers,
diff --git a/server/cmd/server/shutdown_test.go b/server/cmd/server/shutdown_test.go
index c9760b8e3b..21aa5e8a0c 100644
--- a/server/cmd/server/shutdown_test.go
+++ b/server/cmd/server/shutdown_test.go
@@ -20,6 +20,7 @@ func TestShutdownSequence_RunsInTheDocumentedOrder(t *testing.T) {
}
shutdownSequence{
StopAutopilot: record("autopilot"),
+ DrainMaintenance: record("maintenance"),
DrainHTTP: record("http"),
StopOutboundRelay: record("relay"),
CancelWorkers: record("cancel"),
@@ -33,7 +34,7 @@ func TestShutdownSequence_RunsInTheDocumentedOrder(t *testing.T) {
}.run()
want := []string{
- "autopilot", "http", "relay", "cancel", "heartbeats",
+ "autopilot", "maintenance", "http", "relay", "cancel", "heartbeats",
"webhooks", "telegram", "supervisor", "router", "metrics", "pprof",
}
if !slices.Equal(ran, want) {
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 9fe6aa5ba8..6c3d66cec3 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -90,6 +90,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"lark_installation": workspaceDelete,
"lark_outbound_card_message": workspaceDelete,
"lark_user_binding": workspaceDelete,
+ "maintenance_job": workspaceDeleteKeep, // Global maintenance audit history, not workspace-owned.
"member": workspaceDelete,
"agent_mcp_server": workspaceDelete,
"workspace_mcp_server": workspaceDelete,
diff --git a/server/internal/maintenance/http.go b/server/internal/maintenance/http.go
new file mode 100644
index 0000000000..f830946e36
--- /dev/null
+++ b/server/internal/maintenance/http.go
@@ -0,0 +1,159 @@
+package maintenance
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgconn"
+
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// NewServer is a separate listener; never mount its handler on the public router.
+// Empty port disables it. Only the port is configurable, never the bind address.
+func NewServer(port string, service *Service) (*http.Server, error) {
+ if port == "" {
+ return nil, nil
+ }
+ n, err := strconv.Atoi(port)
+ if err != nil || n < 1 || n > 65535 {
+ return nil, fmt.Errorf("MAINTENANCE_PORT must be 1..65535")
+ }
+ return &http.Server{Addr: net.JoinHostPort("127.0.0.1", port), Handler: NewHandler(service),
+ ReadHeaderTimeout: 2 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 20 * time.Second, IdleTimeout: 15 * time.Second}, nil
+}
+func NewHandler(s *Service) http.Handler {
+ mux := http.NewServeMux()
+ mux.HandleFunc("POST /maintenance/jobs", func(w http.ResponseWriter, r *http.Request) {
+ var request CreateRequest
+ if !readRequest(w, r, &request) {
+ return
+ }
+ j, err := s.Create(r.Context(), request)
+ respond(w, j, err)
+ })
+ mux.HandleFunc("GET /maintenance/jobs/{id}", func(w http.ResponseWriter, r *http.Request) {
+ if _, err := util.ParseUUID(r.PathValue("id")); err != nil {
+ respond(w, Job{}, ErrInvalid)
+ return
+ }
+ j, err := s.Get(r.Context(), r.PathValue("id"))
+ respond(w, j, err)
+ })
+ for _, action := range []string{"advance", "pause", "resume", "cancel"} {
+ mux.HandleFunc("POST /maintenance/jobs/{id}/"+action, func(w http.ResponseWriter, r *http.Request) {
+ if _, err := util.ParseUUID(r.PathValue("id")); err != nil {
+ respond(w, Job{}, ErrInvalid)
+ return
+ }
+ var request struct {
+ Revision *int64 `json:"revision"`
+ }
+ if !readRequest(w, r, &request) {
+ return
+ }
+ if request.Revision == nil {
+ respond(w, Job{}, ErrInvalid)
+ return
+ }
+ j, err := s.Mutate(r.Context(), r.PathValue("id"), *request.Revision, action)
+ respond(w, j, err)
+ })
+ }
+ mux.HandleFunc("POST /maintenance/jobs/{id}/configure", func(w http.ResponseWriter, r *http.Request) {
+ if _, err := util.ParseUUID(r.PathValue("id")); err != nil {
+ respond(w, Job{}, ErrInvalid)
+ return
+ }
+ var request struct {
+ Revision *int64 `json:"revision"`
+ Options Options `json:"options"`
+ }
+ if !readRequest(w, r, &request) {
+ return
+ }
+ if request.Revision == nil {
+ respond(w, Job{}, ErrInvalid)
+ return
+ }
+ j, err := s.Configure(r.Context(), r.PathValue("id"), *request.Revision, request.Options)
+ respond(w, j, err)
+ })
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
+ defer cancel()
+ mux.ServeHTTP(w, r.WithContext(ctx))
+ })
+}
+func readRequest(w http.ResponseWriter, r *http.Request, v any) bool {
+ r.Body = http.MaxBytesReader(w, r.Body, 16<<10)
+ var raw json.RawMessage
+ d := json.NewDecoder(r.Body)
+ if err := d.Decode(&raw); err != nil {
+ respond(w, Job{}, ErrInvalid)
+ return false
+ }
+ // Decode the entire body once, rejecting trailing JSON too.
+ var extra any
+ if err := d.Decode(&extra); err == nil {
+ respond(w, Job{}, ErrInvalid)
+ return false
+ } else if err != io.EOF {
+ respond(w, Job{}, ErrInvalid)
+ return false
+ }
+ if string(raw) == "null" {
+ respond(w, Job{}, ErrInvalid)
+ return false
+ }
+ if err := decode(raw, v); err != nil {
+ respond(w, Job{}, err)
+ return false
+ }
+ return true
+}
+func respond(w http.ResponseWriter, j Job, err error) {
+ status := http.StatusOK
+ message := ""
+ if err != nil {
+ message = err.Error()
+ switch {
+ case errors.Is(err, ErrInvalid):
+ status = http.StatusBadRequest
+ case errors.Is(err, ErrNotFound):
+ status = http.StatusNotFound
+ case errors.Is(err, ErrBusy), errors.Is(err, ErrConflict):
+ status = http.StatusConflict
+ case errors.Is(err, ErrThrottled):
+ status = http.StatusTooManyRequests
+ default:
+ status = http.StatusServiceUnavailable
+ }
+ slog.Warn("maintenance request failed", "job_id", j.ID, "revision", j.Revision, "error", err)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(status)
+ var job *Job
+ if j.ID != "" {
+ job = &j
+ }
+ var pe *pgconn.PgError
+ retryable := errors.Is(err, ErrBusy) || errors.Is(err, ErrThrottled)
+ if errors.As(err, &pe) {
+ retryable = pe.Code == "55P03" || pe.Code == "40P01" || pe.Code == "40001" || pe.Code == "57014"
+ }
+ _ = json.NewEncoder(w).Encode(struct {
+ Job *Job `json:"job,omitempty"`
+ Error string `json:"error,omitempty"`
+ Retryable bool `json:"retryable,omitempty"`
+ }{job, message, retryable})
+}
diff --git a/server/internal/maintenance/http_test.go b/server/internal/maintenance/http_test.go
new file mode 100644
index 0000000000..d797b91c5f
--- /dev/null
+++ b/server/internal/maintenance/http_test.go
@@ -0,0 +1,151 @@
+package maintenance
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "testing"
+ "time"
+)
+
+func TestInternalListenerConfiguration(t *testing.T) {
+ s := NewService(nil, StatusCategory{})
+ if server, err := NewServer("", s); err != nil || server != nil {
+ t.Fatal("empty port must disable listener")
+ }
+ for _, port := range []string{"0", "-1", "65536", "0.0.0.0:6061", "localhost:6061", ":6061"} {
+ if _, err := NewServer(port, s); err == nil {
+ t.Fatalf("accepted %q", port)
+ }
+ }
+ server, err := NewServer("6061", s)
+ if err != nil || server.Addr != "127.0.0.1:6061" {
+ t.Fatalf("listener=%+v err=%v", server, err)
+ }
+}
+func TestInternalHTTPRejectsMalformedRequestsWithoutDatabase(t *testing.T) {
+ h := NewHandler(NewService(nil, StatusCategory{}))
+ for _, body := range []string{"null", "[]", "{} {}", "{} garbage", `{"unknown":true}`, string(bytes.Repeat([]byte("x"), 17000))} {
+ t.Run(body[:min(len(body), 30)], func(t *testing.T) {
+ req := httptest.NewRequest("POST", "/maintenance/jobs", bytes.NewBufferString(body))
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ if w.Code != 400 {
+ t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
+ }
+ })
+ }
+ for _, path := range []string{"/maintenance/jobs/not-a-uuid", "/maintenance/jobs/not-a-uuid/advance"} {
+ method := "GET"
+ if path[len(path)-7:] == "advance" {
+ method = "POST"
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, httptest.NewRequest(method, path, bytes.NewBufferString("{}")))
+ if w.Code != 400 {
+ t.Fatalf("%s: %d", path, w.Code)
+ }
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, httptest.NewRequest("POST", "/maintenance/jobs/"+statusID(1)+"/advance", bytes.NewBufferString("{}")))
+ if w.Code != 400 {
+ t.Fatal("missing revision was accepted")
+ }
+}
+func TestInternalHTTPCreateAdvanceReplayAndConfigure(t *testing.T) {
+ pool, s := fixture(t)
+ seed(t, pool, "old")
+ server, err := NewServer("6061", s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ listener, err := net.Listen("tcp4", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ done := make(chan error, 1)
+ go func() { done <- server.Serve(listener) }()
+ t.Cleanup(func() { _ = server.Close(); <-done })
+ base := "http://" + listener.Addr().String()
+ call := func(method, path string, body any, want int) Job {
+ t.Helper()
+ req, err := http.NewRequest(method, base+path, bytes.NewReader(asJSON(body)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // No application token: access is through the independent loopback listener.
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ raw, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != want {
+ t.Fatalf("%s %s: %d %s", method, path, resp.StatusCode, raw)
+ }
+ var out struct {
+ Job Job `json:"job"`
+ }
+ if err = json.Unmarshal(raw, &out); err != nil {
+ t.Fatal(err)
+ }
+ return out.Job
+ }
+ req := request(false)
+ j := call("POST", "/maintenance/jobs", req, 200)
+ first := call("POST", "/maintenance/jobs/"+j.ID+"/advance", map[string]any{"revision": j.Revision}, 200)
+ replay := call("POST", "/maintenance/jobs/"+j.ID+"/advance", map[string]any{"revision": j.Revision}, 409)
+ if replay.Revision != first.Revision {
+ t.Fatal("replay advanced another batch")
+ }
+ paused := call("POST", "/maintenance/jobs/"+j.ID+"/pause", map[string]any{"revision": first.Revision}, 200)
+ opts := Options{BatchSize: 1, DelayMS: 20, LockTimeoutMS: 10, StatementTimeoutMS: 500}
+ configured := call("POST", "/maintenance/jobs/"+j.ID+"/configure", map[string]any{"revision": paused.Revision, "options": opts}, 200)
+ if configured.Options != opts || configured.NextAllowedAt.Before(paused.NextAllowedAt) {
+ t.Fatal("configuration was not durable")
+ }
+ duplicate := call("POST", "/maintenance/jobs", req, 200)
+ if duplicate.ID != j.ID || duplicate.Options != opts {
+ t.Fatal("creation retry after tuning did not return original job")
+ }
+ current := call("GET", "/maintenance/jobs/"+j.ID, nil, 200)
+ if current.Revision != configured.Revision {
+ t.Fatal("GET is not current")
+ }
+ // Build the same standalone driver shipped in the backend image.
+ driver := filepath.Join(t.TempDir(), "maintenance")
+ if output, err := exec.Command("go", "build", "-o", driver, "../../cmd/maintenance").CombinedOutput(); err != nil {
+ t.Fatalf("build driver: %v\n%s", err, output)
+ }
+ port := listener.Addr().(*net.TCPAddr).Port
+ output, err := exec.Command(driver, "run", "--port", strconv.Itoa(port), "--job", j.ID, "--max-batches", "1", "--max-seconds", "15", "--resume").CombinedOutput()
+ var exit *exec.ExitError
+ if !errors.As(err, &exit) || exit.ExitCode() != 2 {
+ t.Fatalf("incomplete canary should exit 2: %v\n%s", err, output)
+ }
+ canary := call("GET", "/maintenance/jobs/"+j.ID, nil, 200)
+ if canary.Status != "ready" || canary.Revision != configured.Revision+2 {
+ t.Fatalf("canary did more than resume + one batch: %+v", canary)
+ }
+ output, err = exec.Command(driver, "run", "--port", strconv.Itoa(port), "--job", j.ID, "--max-batches", "60", "--max-seconds", "15").CombinedOutput()
+ if err != nil {
+ t.Fatalf("driver: %v\n%s", err, output)
+ }
+ completed := call("GET", "/maintenance/jobs/"+j.ID, nil, 200)
+ if completed.Status != "completed" {
+ t.Fatalf("driver did not finish: %s", output)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ if err = server.Shutdown(ctx); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/server/internal/maintenance/job.go b/server/internal/maintenance/job.go
new file mode 100644
index 0000000000..10abcc7393
--- /dev/null
+++ b/server/internal/maintenance/job.go
@@ -0,0 +1,367 @@
+// Package maintenance runs explicitly requested, bounded database maintenance.
+// It has no scheduler: each call advances one transaction on the primary database.
+package maintenance
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+var (
+ ErrInvalid = errors.New("invalid maintenance request")
+ ErrConflict = errors.New("maintenance job conflict")
+ ErrBusy = errors.New("maintenance job busy")
+ ErrThrottled = errors.New("maintenance job rate limited")
+ ErrNotFound = errors.New("maintenance job not found")
+)
+
+type Options struct {
+ BatchSize int `json:"batch_size"`
+ DelayMS int `json:"delay_ms"`
+ LockTimeoutMS int `json:"lock_timeout_ms"`
+ StatementTimeoutMS int `json:"statement_timeout_ms"`
+}
+
+func (o *Options) normalize() error {
+ if o.BatchSize == 0 {
+ o.BatchSize = 500
+ }
+ if o.DelayMS == 0 {
+ o.DelayMS = 100
+ }
+ if o.LockTimeoutMS == 0 {
+ o.LockTimeoutMS = 500
+ }
+ if o.StatementTimeoutMS == 0 {
+ o.StatementTimeoutMS = 3000
+ }
+ if o.BatchSize < 1 || o.BatchSize > 5000 || o.DelayMS < 1 || o.DelayMS > 60000 ||
+ o.LockTimeoutMS < 1 || o.StatementTimeoutMS < o.LockTimeoutMS || o.StatementTimeoutMS > 5000 {
+ return fmt.Errorf("%w: batch_size 1..5000, delay_ms 1..60000, 1 <= lock_timeout_ms <= statement_timeout_ms <= 5000", ErrInvalid)
+ }
+ return nil
+}
+
+type Job struct {
+ ID string `json:"id"`
+ Type string `json:"job_type"`
+ Version int `json:"job_version"`
+ Scope string `json:"scope_key"`
+ IdempotencyKey string `json:"idempotency_key"`
+ RequestHash string `json:"-"`
+ Status string `json:"status"`
+ Revision int64 `json:"revision"`
+ DryRun bool `json:"dry_run"`
+ Options Options `json:"options"`
+ Parameters json.RawMessage `json:"parameters"`
+ Checkpoint json.RawMessage `json:"checkpoint"`
+ Progress json.RawMessage `json:"progress"`
+ Result json.RawMessage `json:"result"`
+ LastError string `json:"last_error"`
+ NextAllowedAt time.Time `json:"next_allowed_at"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+ CompletedAt *time.Time `json:"completed_at,omitempty"`
+}
+type CreateRequest struct {
+ Type string `json:"job_type"`
+ Version int `json:"job_version"`
+ Scope string `json:"scope_key"`
+ IdempotencyKey string `json:"idempotency_key"`
+ DryRun *bool `json:"dry_run,omitempty"`
+ Options Options `json:"options"`
+ Parameters json.RawMessage `json:"parameters"`
+}
+
+// Processor implementations must only write through the supplied transaction.
+// External side effects cannot share this checkpoint's atomicity guarantee.
+type Processor interface {
+ Type() string
+ Version() int
+ Validate(scope string, dryRun bool, parameters json.RawMessage) (json.RawMessage, error)
+ Preflight(context.Context, pgx.Tx) error
+ Step(context.Context, pgx.Tx, Job) (checkpoint, progress, result json.RawMessage, complete bool, err error)
+}
+type Service struct {
+ pool *pgxpool.Pool
+ processors map[string]Processor
+}
+
+func NewService(pool *pgxpool.Pool, processors ...Processor) *Service {
+ s := &Service{pool: pool, processors: make(map[string]Processor)}
+ for _, p := range processors {
+ if _, ok := s.processors[p.Type()]; ok {
+ panic("duplicate maintenance processor")
+ }
+ s.processors[p.Type()] = p
+ }
+ return s
+}
+func decode(raw []byte, target any) error {
+ if len(bytes.TrimSpace(raw)) == 0 || bytes.TrimSpace(raw)[0] != '{' {
+ return fmt.Errorf("%w: expected JSON object", ErrInvalid)
+ }
+ d := json.NewDecoder(bytes.NewReader(raw))
+ d.DisallowUnknownFields()
+ if err := d.Decode(target); err != nil {
+ return fmt.Errorf("%w: %v", ErrInvalid, err)
+ }
+ if err := d.Decode(new(any)); err != io.EOF {
+ return fmt.Errorf("%w: expected one JSON object", ErrInvalid)
+ }
+ return nil
+}
+func asJSON(v any) json.RawMessage { b, _ := json.Marshal(v); return b }
+
+const columns = `id::text, job_type, job_version, scope_key, idempotency_key, request_hash, status, revision,
+dry_run, options, parameters, checkpoint, progress, result, last_error, next_allowed_at,
+created_at, updated_at, completed_at`
+
+func scan(row pgx.Row) (Job, error) {
+ var j Job
+ var opts []byte
+ err := row.Scan(&j.ID, &j.Type, &j.Version, &j.Scope, &j.IdempotencyKey, &j.RequestHash, &j.Status, &j.Revision,
+ &j.DryRun, &opts, &j.Parameters, &j.Checkpoint, &j.Progress, &j.Result, &j.LastError,
+ &j.NextAllowedAt, &j.CreatedAt, &j.UpdatedAt, &j.CompletedAt)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return j, ErrNotFound
+ }
+ if err != nil {
+ return j, err
+ }
+ err = decode(opts, &j.Options)
+ return j, err
+}
+func (s *Service) processor(j Job) (Processor, error) {
+ p, ok := s.processors[j.Type]
+ if !ok || p.Version() != j.Version {
+ return nil, fmt.Errorf("%w: unsupported job type/version", ErrConflict)
+ }
+ return p, nil
+}
+func (s *Service) Get(ctx context.Context, id string) (Job, error) {
+ return scan(s.pool.QueryRow(ctx, "SELECT "+columns+" FROM maintenance_job WHERE id=$1::uuid", id))
+}
+func setTimeouts(ctx context.Context, tx pgx.Tx, o Options) error {
+ _, err := tx.Exec(ctx, `SELECT set_config('lock_timeout', $1, true), set_config('statement_timeout', $2, true)`,
+ fmt.Sprintf("%dms", o.LockTimeoutMS), fmt.Sprintf("%dms", o.StatementTimeoutMS))
+ return err
+}
+func classify(err error) error {
+ var pe *pgconn.PgError
+ if errors.As(err, &pe) {
+ switch pe.Code {
+ case "55P03":
+ return ErrBusy
+ case "23505":
+ return ErrConflict
+ }
+ }
+ return err
+}
+func (s *Service) Create(ctx context.Context, r CreateRequest) (Job, error) {
+ if r.IdempotencyKey == "" || len(r.IdempotencyKey) > 200 || len(r.Scope) > 200 {
+ return Job{}, ErrInvalid
+ }
+ if err := r.Options.normalize(); err != nil {
+ return Job{}, err
+ }
+ dry := r.DryRun == nil || *r.DryRun
+ j := Job{Type: r.Type, Version: r.Version, Scope: r.Scope, DryRun: dry, Options: r.Options}
+ p, err := s.processor(j)
+ if err != nil {
+ return Job{}, err
+ }
+ if len(r.Parameters) == 0 {
+ r.Parameters = asJSON(struct{}{})
+ }
+ params, err := p.Validate(r.Scope, dry, r.Parameters)
+ if err != nil {
+ return Job{}, err
+ }
+ // Keep creation identity stable even after operational options are tuned.
+ hash := fmt.Sprintf("%x", sha256.Sum256(asJSON([]any{r.Type, r.Version, r.Scope, dry, r.Options, params})))
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return Job{}, err
+ }
+ defer tx.Rollback(context.Background())
+ if err = setTimeouts(ctx, tx, r.Options); err != nil {
+ return Job{}, err
+ }
+ // Every processor relies on these shared identity/concurrency constraints.
+ var count int
+ if err = tx.QueryRow(ctx, `SELECT count(*) FROM pg_index i
+ WHERE i.indrelid='maintenance_job'::regclass AND i.indexrelid IN
+ (to_regclass('idx_maintenance_job_id'),to_regclass('idx_maintenance_job_idempotency'),to_regclass('idx_maintenance_job_active'))
+ AND i.indisvalid AND i.indisunique`).Scan(&count); err != nil {
+ return Job{}, err
+ }
+ if count != 3 {
+ return Job{}, fmt.Errorf("maintenance indexes are missing or invalid; finish migrations 480-482")
+ }
+ // Serialize creation requests for this type/scope; the unique indexes remain the final guard.
+ var locked bool
+ err = tx.QueryRow(ctx, "SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))", "maintenance:"+r.Type+":"+r.Scope).Scan(&locked)
+ if err != nil {
+ return Job{}, err
+ }
+ if !locked {
+ return Job{}, ErrBusy
+ }
+ existing, err := scan(tx.QueryRow(ctx, "SELECT "+columns+" FROM maintenance_job WHERE idempotency_key=$1", r.IdempotencyKey))
+ if err == nil {
+ if existing.RequestHash != hash {
+ return existing, ErrConflict
+ }
+ return existing, nil
+ }
+ if !errors.Is(err, ErrNotFound) {
+ return Job{}, err
+ }
+ if err = p.Preflight(ctx, tx); err != nil {
+ return Job{}, err
+ }
+ j, err = scan(tx.QueryRow(ctx, `INSERT INTO maintenance_job
+ (job_type,job_version,scope_key,idempotency_key,status,dry_run,options,parameters,request_hash)
+ VALUES ($1,$2,$3,$4,'ready',$5,$6,$7,$8) RETURNING `+columns,
+ r.Type, r.Version, r.Scope, r.IdempotencyKey, dry, asJSON(r.Options), params, hash))
+ if err != nil {
+ return Job{}, classify(err)
+ }
+ return j, tx.Commit(ctx)
+}
+
+// Mutate uses a row lock and a caller-supplied revision. Stale retries return
+// the durable state without advancing again, including after an ambiguous commit.
+func (s *Service) Mutate(ctx context.Context, id string, revision int64, action string) (Job, error) {
+ return s.mutate(ctx, id, revision, action, nil)
+}
+
+// Configure changes operational limits only while paused; task parameters and
+// processor versions are immutable for a run.
+func (s *Service) Configure(ctx context.Context, id string, revision int64, options Options) (Job, error) {
+ if err := options.normalize(); err != nil {
+ return Job{}, err
+ }
+ return s.mutate(ctx, id, revision, "configure", &options)
+}
+
+func (s *Service) mutate(ctx context.Context, id string, revision int64, action string, options *Options) (Job, error) {
+ if revision < 0 {
+ return Job{}, ErrInvalid
+ }
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return Job{}, err
+ }
+ defer tx.Rollback(context.Background())
+ if err = setTimeouts(ctx, tx, Options{LockTimeoutMS: 500, StatementTimeoutMS: 5000}); err != nil {
+ return Job{}, err
+ }
+ j, err := scan(tx.QueryRow(ctx, "SELECT "+columns+" FROM maintenance_job WHERE id=$1::uuid FOR UPDATE NOWAIT", id))
+ if err != nil {
+ return Job{}, classify(err)
+ }
+ if j.Revision != revision {
+ return j, ErrConflict
+ }
+ if j.Status == "completed" || j.Status == "cancelled" {
+ return j, ErrConflict
+ }
+ var stepErr error
+ switch action {
+ case "configure":
+ if j.Status != "paused" || options == nil {
+ return j, ErrConflict
+ }
+ j.Options = *options
+ case "pause":
+ j.Status = "paused"
+ case "cancel":
+ j.Status = "cancelled"
+ case "resume":
+ j.Status = "ready"
+ case "advance":
+ if j.Status != "ready" {
+ return j, ErrConflict
+ }
+ p, e := s.processor(j)
+ if e != nil {
+ return j, e
+ }
+ var eligible bool
+ if err = tx.QueryRow(ctx, "SELECT clock_timestamp() >= $1", j.NextAllowedAt).Scan(&eligible); err != nil {
+ return j, err
+ }
+ if !eligible {
+ return j, ErrThrottled
+ }
+ if _, e = p.Validate(j.Scope, j.DryRun, j.Parameters); e != nil {
+ return j, e
+ }
+ if e = j.Options.normalize(); e != nil {
+ return j, e
+ }
+ // Savepoint lets failures retain diagnostics without retaining partial data.
+ batch, e := tx.Begin(ctx)
+ if e != nil {
+ return j, e
+ }
+ e = setTimeouts(ctx, batch, j.Options)
+ if e == nil {
+ e = p.Preflight(ctx, batch)
+ }
+ var cp, progress, result json.RawMessage
+ var complete bool
+ if e == nil {
+ cp, progress, result, complete, e = p.Step(ctx, batch, j)
+ }
+ if e != nil {
+ if rollbackErr := batch.Rollback(ctx); rollbackErr != nil {
+ return j, e
+ }
+ stepErr = e
+ j.LastError = e.Error()
+ // Repeated failures require an explicit operator resume.
+ j.Status = "paused"
+ } else {
+ if e = batch.Commit(ctx); e != nil {
+ return j, e
+ }
+ j.Checkpoint, j.Progress, j.Result = cp, progress, result
+ j.LastError = ""
+ if complete {
+ j.Status = "completed"
+ }
+ }
+ default:
+ return j, ErrInvalid
+ }
+ j, err = scan(tx.QueryRow(ctx, `UPDATE maintenance_job SET status=$2, revision=revision+1,
+ checkpoint=$3,progress=$4,result=$5,last_error=$6,updated_at=clock_timestamp(),
+ next_allowed_at=CASE WHEN $7 THEN GREATEST(next_allowed_at,clock_timestamp()+$8*interval '1 millisecond') ELSE next_allowed_at END,
+ options=$9,
+ completed_at=CASE WHEN $2 IN ('completed','cancelled') THEN clock_timestamp() ELSE completed_at END
+ WHERE id=$1::uuid RETURNING `+columns, id, j.Status, j.Checkpoint, j.Progress, j.Result, j.LastError,
+ action == "advance" || action == "configure", j.Options.DelayMS, asJSON(j.Options)))
+ if err != nil {
+ return j, err
+ }
+ if err = tx.Commit(ctx); err != nil {
+ return Job{}, err
+ }
+ slog.Info("maintenance job operation committed", "job_id", j.ID, "job_type", j.Type, "action", action, "status", j.Status, "revision", j.Revision, "progress", string(j.Progress))
+ return j, stepErr
+}
diff --git a/server/internal/maintenance/job_test.go b/server/internal/maintenance/job_test.go
new file mode 100644
index 0000000000..6b208882dc
--- /dev/null
+++ b/server/internal/maintenance/job_test.go
@@ -0,0 +1,556 @@
+package maintenance
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func fixture(t *testing.T) (*pgxpool.Pool, *Service) {
+ t.Helper()
+ url := os.Getenv("DATABASE_URL")
+ if url == "" {
+ t.Skip("DATABASE_URL required; run through make env-exec")
+ }
+ ctx := context.Background()
+ admin, err := pgxpool.New(ctx, url)
+ if err != nil {
+ t.Fatal(err)
+ }
+ schema := "maintenance_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
+ if _, err = admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
+ admin.Close()
+ t.Fatal(err)
+ }
+ config, err := pgxpool.ParseConfig(url)
+ if err != nil {
+ t.Fatal(err)
+ }
+ config.ConnConfig.RuntimeParams["search_path"] = schema + ",pg_catalog"
+ config.MaxConns = 8
+ pool, err := pgxpool.NewWithConfig(ctx, config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ pool.Close()
+ _, err := admin.Exec(context.Background(), "DROP SCHEMA "+schema+" CASCADE")
+ admin.Close()
+ if err != nil {
+ t.Error(err)
+ }
+ })
+ exec := func(sql string) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, sql); err != nil {
+ t.Fatal(err)
+ }
+ }
+ exec("CREATE TABLE schema_migrations(version text)")
+ for _, name := range []string{"332_issue_status", "333_issue_status_pkey_index", "478_issue_status_category_expand", "485_maintenance_job", "486_maintenance_job_id_index", "487_maintenance_job_idempotency_index", "488_maintenance_job_active_index"} {
+ body, err := os.ReadFile(filepath.Join("..", "..", "migrations", name+".up.sql"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ exec(string(body))
+ }
+ exec("INSERT INTO schema_migrations VALUES ('478_issue_status_category_expand')")
+ return pool, NewService(pool, StatusCategory{})
+}
+func statusID(i int) string { return fmt.Sprintf("00000000-0000-0000-0000-%012d", i) }
+func seed(t *testing.T, pool *pgxpool.Pool, mode string) {
+ t.Helper()
+ dbfx := testutil.New(pool, uuid.NewString(), uuid.NewString())
+ keys := []string{"backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"}
+ for i, key := range keys {
+ category := key
+ if mode == "new" || (mode == "mixed" && i%2 == 0) {
+ category = categoryMapping[key]
+ }
+ dbfx.Insert(t, "issue_status", testutil.Cols{"id": statusID(i + 1), "workspace_id": dbfx.WorkspaceID,
+ "key": key, "name": key, "category": category, "color": "#123456", "is_system": true})
+ dbfx.Insert(t, "issue_status", testutil.Cols{"id": statusID(i + 8), "workspace_id": uuid.NewString(),
+ "key": "custom_" + key, "name": key, "category": category, "color": "#123456", "archived_at": testutil.Raw("now()")})
+ }
+}
+func request(dry bool) CreateRequest {
+ return CreateRequest{Type: StatusCategoryType, Version: 1, Scope: "database", IdempotencyKey: uuid.NewString(),
+ DryRun: &dry, Options: Options{BatchSize: 3, DelayMS: 1, LockTimeoutMS: 50, StatementTimeoutMS: 1000},
+ Parameters: asJSON(statusParameters{WritersUpgraded: !dry})}
+}
+func create(t *testing.T, s *Service, dry bool) Job {
+ t.Helper()
+ j, err := s.Create(context.Background(), request(dry))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return j
+}
+func step(t *testing.T, s *Service, j Job) Job {
+ t.Helper()
+ for i := 0; i < 5; i++ {
+ next, err := s.Mutate(context.Background(), j.ID, j.Revision, "advance")
+ if errors.Is(err, ErrThrottled) {
+ time.Sleep(2 * time.Millisecond)
+ continue
+ }
+ if err != nil {
+ t.Fatalf("advance: %v; job=%+v", err, next)
+ }
+ return next
+ }
+ t.Fatal("throttled beyond bounded retry")
+ return Job{}
+}
+func finish(t *testing.T, s *Service, j Job) Job {
+ t.Helper()
+ for i := 0; i < 30; i++ {
+ if j.Status == "completed" {
+ return j
+ }
+ j = step(t, s, j)
+ }
+ t.Fatal("job failed to terminate")
+ return Job{}
+}
+func snapshot(t *testing.T, pool *pgxpool.Pool, excludeCategory bool) string {
+ t.Helper()
+ var s string
+ expr := "to_jsonb(s)"
+ if excludeCategory {
+ expr += "-'category'"
+ }
+ if err := pool.QueryRow(context.Background(), "SELECT coalesce(jsonb_agg("+expr+" ORDER BY id),'[]')::text FROM issue_status s").Scan(&s); err != nil {
+ t.Fatal(err)
+ }
+ return s
+}
+func TestCategoryBackfillOldMixedNewAndDryRun(t *testing.T) {
+ for _, mode := range []string{"old", "mixed", "new"} {
+ t.Run(mode, func(t *testing.T) {
+ pool, s := fixture(t)
+ seed(t, pool, mode)
+ before := snapshot(t, pool, false)
+ identity := snapshot(t, pool, true)
+ dry := finish(t, s, create(t, s, true))
+ if snapshot(t, pool, false) != before {
+ t.Fatal("dry-run changed catalog")
+ }
+ var report statusProgress
+ if err := decode(dry.Progress, &report); err != nil {
+ t.Fatal(err)
+ }
+ if report.Scanned != 14 || report.System != 7 || report.Archived != 7 || report.Updated != 0 {
+ t.Fatalf("dry report: %+v", report)
+ }
+ j := create(t, s, false)
+ for j.Status != "completed" {
+ var p statusProgress
+ _ = decode(j.Progress, &p)
+ next := step(t, s, j)
+ var np statusProgress
+ _ = decode(next.Progress, &np)
+ if np.Scanned-p.Scanned > 3 || np.Updated-p.Updated > 3 || np.Verified-p.Verified > 3 {
+ t.Fatal("unbounded batch")
+ }
+ // A different service instance represents another replica/restarted container.
+ s = NewService(pool, StatusCategory{})
+ j = next
+ }
+ if snapshot(t, pool, true) != identity {
+ t.Fatal("identity, archive, timestamps or business fields changed")
+ }
+ var remaining int
+ if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM issue_status WHERE category != issue_status_category(category)").Scan(&remaining); err != nil || remaining != 0 {
+ t.Fatalf("remaining=%d: %v", remaining, err)
+ }
+ var p statusProgress
+ _ = decode(j.Progress, &p)
+ if p.Verified != 14 || p.Updated != report.WouldUpdate {
+ t.Fatalf("progress=%+v dry=%+v", p, report)
+ }
+ again := finish(t, s, create(t, s, false))
+ _ = decode(again.Progress, &p)
+ if p.Updated != 0 {
+ t.Fatal("second pass rewrote canonical rows")
+ }
+ })
+ }
+}
+func TestJobIdempotencyVersionPauseAndDatabaseThrottle(t *testing.T) {
+ pool, s := fixture(t)
+ seed(t, pool, "old")
+ ctx := context.Background()
+ req := request(false)
+ req.Options.DelayMS = 60000
+ j, err := s.Create(ctx, req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ same, err := s.Create(ctx, req)
+ if err != nil || same.ID != j.ID {
+ t.Fatalf("create retry: %+v %v", same, err)
+ }
+ different := req
+ different.Options.BatchSize++
+ if _, err = s.Create(ctx, different); !errors.Is(err, ErrConflict) {
+ t.Fatalf("changed duplicate request: %v", err)
+ }
+ other := request(false)
+ if _, err = s.Create(ctx, other); !errors.Is(err, ErrConflict) {
+ t.Fatalf("duplicate active scope: %v", err)
+ }
+ next := step(t, s, j)
+ replay, err := NewService(pool, StatusCategory{}).Mutate(ctx, j.ID, j.Revision, "advance")
+ if !errors.Is(err, ErrConflict) || replay.Revision != next.Revision {
+ t.Fatalf("lost-response replay advanced: %+v %v", replay, err)
+ }
+ if _, err = s.Mutate(ctx, j.ID, next.Revision, "advance"); !errors.Is(err, ErrThrottled) {
+ t.Fatalf("cross-replica delay: %v", err)
+ }
+ paused, err := s.Mutate(ctx, j.ID, next.Revision, "pause")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.Mutate(ctx, j.ID, paused.Revision, "advance"); !errors.Is(err, ErrConflict) {
+ t.Fatalf("paused advanced: %v", err)
+ }
+ resumed, err := s.Mutate(ctx, j.ID, paused.Revision, "resume")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.Mutate(ctx, j.ID, resumed.Revision, "advance"); !errors.Is(err, ErrThrottled) {
+ t.Fatal("resume bypassed delay")
+ }
+ cancelled, err := s.Mutate(ctx, j.ID, resumed.Revision, "cancel")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.Mutate(ctx, j.ID, cancelled.Revision, "resume"); !errors.Is(err, ErrConflict) {
+ t.Fatal("terminal history reopened")
+ }
+ if _, err = s.Create(ctx, other); err != nil {
+ t.Fatal("new run after cancellation:", err)
+ }
+}
+func TestLockTimeoutRollsBackDataAndCheckpoint(t *testing.T) {
+ pool, s := fixture(t)
+ seed(t, pool, "old")
+ j := create(t, s, false)
+ ctx := context.Background()
+ blocker, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer blocker.Rollback(ctx)
+ if _, err = blocker.Exec(ctx, "SELECT id FROM issue_status WHERE id=$1::uuid FOR UPDATE", statusID(2)); err != nil {
+ t.Fatal(err)
+ }
+ before := snapshot(t, pool, false)
+ start := time.Now()
+ failed, err := s.Mutate(ctx, j.ID, j.Revision, "advance")
+ if err == nil || failed.Status != "paused" || failed.LastError == "" {
+ t.Fatalf("expected paused timeout: %+v %v", failed, err)
+ }
+ if elapsed := time.Since(start); elapsed > 2*time.Second {
+ t.Fatalf("timeout took %s", elapsed)
+ }
+ if string(failed.Checkpoint) != "{}" || string(failed.Progress) != "{}" || snapshot(t, pool, false) != before {
+ t.Fatal("partial data/checkpoint committed")
+ }
+ t.Logf("row-lock contention bounded to %s; partial updates rolled back", time.Since(start))
+ if err = blocker.Rollback(ctx); err != nil {
+ t.Fatal(err)
+ }
+ resumed, err := s.Mutate(ctx, j.ID, failed.Revision, "resume")
+ if err != nil {
+ t.Fatal(err)
+ }
+ finish(t, s, resumed)
+}
+
+type wrappedProcessor struct {
+ StatusCategory
+ hook func(context.Context, pgx.Tx, Job) error
+}
+
+func (p wrappedProcessor) Step(ctx context.Context, tx pgx.Tx, j Job) (json.RawMessage, json.RawMessage, json.RawMessage, bool, error) {
+ cp, progress, result, done, err := p.StatusCategory.Step(ctx, tx, j)
+ if err == nil {
+ err = p.hook(ctx, tx, j)
+ }
+ return cp, progress, result, done, err
+}
+func TestConcurrentReplicaAndConnectionLoss(t *testing.T) {
+ pool, s := fixture(t)
+ seed(t, pool, "old")
+ j := create(t, s, false)
+ before := snapshot(t, pool, false)
+ entered := make(chan struct{})
+ release := make(chan struct{})
+ crashing := NewService(pool, wrappedProcessor{hook: func(ctx context.Context, tx pgx.Tx, _ Job) error {
+ close(entered)
+ <-release
+ // Terminate only this test's own batch connection, after data UPDATE and
+ // before checkpoint/commit, emulating container/connection loss.
+ var pid int
+ if err := tx.QueryRow(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil {
+ return err
+ }
+ _, err := pool.Exec(ctx, "SELECT pg_terminate_backend($1)", pid)
+ if err != nil {
+ return err
+ }
+ _, err = tx.Exec(ctx, "SELECT 1")
+ return err
+ }})
+ result := make(chan error, 1)
+ go func() { _, err := crashing.Mutate(context.Background(), j.ID, j.Revision, "advance"); result <- err }()
+ <-entered
+ _, err := NewService(pool, StatusCategory{}).Mutate(context.Background(), j.ID, j.Revision, "advance")
+ if !errors.Is(err, ErrBusy) {
+ close(release)
+ <-result
+ t.Fatalf("concurrent replica: %v", err)
+ }
+ // Normal writes outside the batch remain available, with no ACCESS EXCLUSIVE lock.
+ var exclusive int
+ if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM pg_locks WHERE relation='issue_status'::regclass AND mode='AccessExclusiveLock'`).Scan(&exclusive); err != nil || exclusive != 0 {
+ t.Errorf("exclusive=%d: %v", exclusive, err)
+ }
+ if _, err := pool.Exec(context.Background(), "UPDATE issue_status SET name='business write' WHERE id=$1::uuid", statusID(14)); err != nil {
+ t.Error(err)
+ }
+ close(release)
+ if err := <-result; err == nil {
+ t.Fatal("connection loss returned success")
+ }
+ current, err := s.Get(context.Background(), j.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if current.Revision != 0 || string(current.Checkpoint) != "{}" {
+ t.Fatal("uncommitted checkpoint survived crash")
+ }
+ var category string
+ if err := pool.QueryRow(context.Background(), "SELECT category FROM issue_status WHERE id=$1::uuid", statusID(1)).Scan(&category); err != nil || category != "backlog" {
+ t.Fatalf("uncommitted update survived: %s %v; before=%s", category, err, before)
+ }
+ finish(t, s, current)
+}
+func TestValidationDetectsResidualBehindCursorAndBadPrerequisites(t *testing.T) {
+ pool, s := fixture(t)
+ seed(t, pool, "old")
+ ctx := context.Background()
+ req := request(false)
+ req.Parameters = asJSON(statusParameters{})
+ if _, err := s.Create(ctx, req); !errors.Is(err, ErrInvalid) {
+ t.Fatal("missing writer attestation accepted")
+ }
+ j := create(t, s, false)
+ for {
+ var cp statusCheckpoint
+ _ = decode(j.Checkpoint, &cp)
+ if cp.Phase == "verify" {
+ break
+ }
+ j = step(t, s, j)
+ }
+ // A legacy writer touches a row behind the completed scan.
+ if _, err := pool.Exec(ctx, "UPDATE issue_status SET category='backlog' WHERE id=$1::uuid", statusID(1)); err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(2 * time.Millisecond)
+ failed, err := s.Mutate(ctx, j.ID, j.Revision, "advance")
+ if err == nil || failed.Status != "paused" || !strings.Contains(failed.LastError, "legacy category remains") {
+ t.Fatalf("false completion: %+v %v", failed, err)
+ }
+ // A different handler version cannot reinterpret stored checkpoint data.
+ if _, err := pool.Exec(ctx, "UPDATE maintenance_job SET job_version=2 WHERE id=$1::uuid", j.ID); err != nil {
+ t.Fatal(err)
+ }
+ resumed, err := s.Mutate(ctx, j.ID, failed.Revision, "resume")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.Mutate(ctx, j.ID, resumed.Revision, "advance"); !errors.Is(err, ErrConflict) {
+ t.Fatalf("unsupported checkpoint version: %v", err)
+ }
+}
+func TestPreflightChecksActualSchemaAndLedger(t *testing.T) {
+ pool, s := fixture(t)
+ ctx := context.Background()
+ if _, err := pool.Exec(ctx, "DELETE FROM schema_migrations"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.Create(ctx, request(true)); err == nil {
+ t.Fatal("missing 478 accepted")
+ }
+ if _, err := pool.Exec(ctx, "INSERT INTO schema_migrations VALUES ('478_issue_status_category_expand')"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pool.Exec(ctx, `ALTER TABLE issue_status DROP CONSTRAINT issue_status_category_check;
+ ALTER TABLE issue_status ADD CONSTRAINT issue_status_category_check CHECK(category IN ('backlog','todo','in_progress','in_review','blocked','done','cancelled'))`); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.Create(ctx, request(true)); err == nil {
+ t.Fatal("ledger hid incompatible CHECK")
+ }
+}
+
+func TestConcurrentBusinessWriteWinsOverObservedLegacyValue(t *testing.T) {
+ pool, s := fixture(t)
+ seed(t, pool, "old")
+ ctx := context.Background()
+ req := request(false)
+ req.Options.BatchSize = 10
+ req.Options.LockTimeoutMS = 1000
+ req.Options.StatementTimeoutMS = 3000
+ j, err := s.Create(ctx, req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ writer, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer writer.Rollback(ctx)
+ if _, err = writer.Exec(ctx, "UPDATE issue_status SET category='done',name='concurrent edit' WHERE id=$1::uuid", statusID(8)); err != nil {
+ t.Fatal(err)
+ }
+ outcome := make(chan error, 1)
+ go func() { _, err := s.Mutate(ctx, j.ID, j.Revision, "advance"); outcome <- err }()
+ // Wait only for this isolated schema's backfill UPDATE to block behind writer.
+ deadline := time.Now().Add(2 * time.Second)
+ waiting := false
+ for time.Now().Before(deadline) {
+ var count int
+ if err = pool.QueryRow(ctx, `SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()
+ AND wait_event_type='Lock' AND query LIKE 'UPDATE issue_status SET category=issue_status_category%'`).Scan(&count); err != nil {
+ break
+ }
+ if count > 0 {
+ waiting = true
+ break
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ if err = writer.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err = <-outcome; err != nil {
+ t.Fatal(err)
+ }
+ if !waiting {
+ t.Fatal("did not exercise concurrent recheck after lock wait")
+ }
+ var category, name string
+ if err = pool.QueryRow(ctx, "SELECT category,name FROM issue_status WHERE id=$1::uuid", statusID(8)).Scan(&category, &name); err != nil {
+ t.Fatal(err)
+ }
+ if category != "done" || name != "concurrent edit" {
+ t.Fatalf("overwrote business write: %s %s", category, name)
+ }
+}
+func TestUnknownStoredDataCannotComplete(t *testing.T) {
+ pool, s := fixture(t)
+ seed(t, pool, "old")
+ ctx := context.Background()
+ // Simulate pre-existing invalid data under NOT VALID compatibility CHECKs.
+ if _, err := pool.Exec(ctx, `ALTER TABLE issue_status DROP CONSTRAINT issue_status_category_check;
+ UPDATE issue_status SET category='unexpected' WHERE id='00000000-0000-0000-0000-000000000008'`); err != nil {
+ t.Fatal(err)
+ }
+ sql, err := os.ReadFile("../../migrations/478_issue_status_category_expand.up.sql")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = pool.Exec(ctx, string(sql)); err != nil {
+ t.Fatal(err)
+ }
+ j := create(t, s, true)
+ for i := 0; i < 10; i++ {
+ time.Sleep(2 * time.Millisecond)
+ next, err := s.Mutate(ctx, j.ID, j.Revision, "advance")
+ if err != nil {
+ if next.Status != "paused" || !strings.Contains(next.LastError, "unknown category") {
+ t.Fatalf("unexpected error: %+v %v", next, err)
+ }
+ return
+ }
+ j = next
+ }
+ t.Fatal("invalid data accepted")
+}
+func TestBoundedKeysetUsesExistingIndex(t *testing.T) {
+ pool, _ := fixture(t)
+ ctx := context.Background()
+ // Bulk fixture is deliberately large enough for the planner to prefer the
+ // existing ID index, without forcing planner switches.
+ if _, err := pool.Exec(ctx, `INSERT INTO issue_status(id,workspace_id,key,name,category,color)
+ SELECT md5(n::text)::uuid,'00000000-0000-0000-0000-000000000001'::uuid,
+ 'status_'||n,'Status '||n,'unstarted','#123456' FROM generate_series(1,10000) n;
+ ANALYZE issue_status`); err != nil {
+ t.Fatal(err)
+ }
+ var plan string
+ if err := pool.QueryRow(ctx, `EXPLAIN (FORMAT JSON) SELECT id::text,key,category,is_system,archived_at IS NOT NULL
+ FROM issue_status WHERE id>'80000000-0000-0000-0000-000000000000'::uuid ORDER BY issue_status.id LIMIT 100`).Scan(&plan); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(plan, "Index Scan") || !strings.Contains(plan, "issue_status_pkey_uidx") || strings.Contains(plan, "Seq Scan") {
+ t.Fatalf("keyset page did not use bounded index access: %s", plan)
+ }
+ t.Log("10,000-row fixture: Limit -> Index Scan using issue_status_pkey_uidx, no sequential scan")
+}
+
+type counterProcessor struct{}
+
+func (counterProcessor) Type() string { return "example_repair" }
+func (counterProcessor) Version() int { return 2 }
+func (counterProcessor) Validate(scope string, dry bool, p json.RawMessage) (json.RawMessage, error) {
+ if scope != "workspace:example" {
+ return nil, ErrInvalid
+ }
+ var params struct {
+ Label string `json:"label"`
+ }
+ if err := decode(p, &params); err != nil {
+ return nil, err
+ }
+ return asJSON(params), nil
+}
+func (counterProcessor) Preflight(context.Context, pgx.Tx) error { return nil }
+func (counterProcessor) Step(ctx context.Context, tx pgx.Tx, j Job) (json.RawMessage, json.RawMessage, json.RawMessage, bool, error) {
+ return asJSON(map[string]any{"timestamp": "2026-09-15T00:00:00Z", "sequence": 4}),
+ asJSON(map[string]int{"repaired": 4}), asJSON(map[string]bool{"verified": true}), true, nil
+}
+func TestSharedTableSupportsDifferentProcessorAndCursor(t *testing.T) {
+ pool, s := fixture(t)
+ category := create(t, s, true)
+ service := NewService(pool, StatusCategory{}, counterProcessor{})
+ j, err := service.Create(context.Background(), CreateRequest{Type: "example_repair", Version: 2, Scope: "workspace:example",
+ IdempotencyKey: uuid.NewString(), Parameters: asJSON(map[string]string{"label": "example"})})
+ if err != nil {
+ t.Fatal(err)
+ }
+ j = step(t, service, j)
+ if j.Status != "completed" || !strings.Contains(string(j.Checkpoint), "timestamp") {
+ t.Fatalf("generic processor failed: %+v", j)
+ }
+ unchanged, err := s.Get(context.Background(), category.ID)
+ if err != nil || unchanged.Revision != 0 {
+ t.Fatal("other job was modified")
+ }
+}
diff --git a/server/internal/maintenance/status_category.go b/server/internal/maintenance/status_category.go
new file mode 100644
index 0000000000..f2e043a735
--- /dev/null
+++ b/server/internal/maintenance/status_category.go
@@ -0,0 +1,200 @@
+package maintenance
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+)
+
+const StatusCategoryType = "issue_status_category"
+
+type StatusCategory struct{}
+
+func (StatusCategory) Type() string { return StatusCategoryType }
+func (StatusCategory) Version() int { return 1 }
+
+type statusParameters struct {
+ WritersUpgraded bool `json:"writers_upgraded"`
+}
+
+func (StatusCategory) Validate(scope string, dry bool, raw json.RawMessage) (json.RawMessage, error) {
+ var p statusParameters
+ if err := decode(raw, &p); err != nil {
+ return nil, err
+ }
+ if scope != "database" {
+ return nil, fmt.Errorf("%w: this processor requires scope_key=database", ErrInvalid)
+ }
+ if !dry && !p.WritersUpgraded {
+ return nil, fmt.Errorf("%w: confirm PR1 is fully deployed using writers_upgraded=true", ErrInvalid)
+ }
+ return asJSON(p), nil
+}
+func (StatusCategory) Preflight(ctx context.Context, tx pgx.Tx) error {
+ var applied bool
+ if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version='478_issue_status_category_expand')`).Scan(&applied); err != nil {
+ return err
+ }
+ if !applied {
+ return fmt.Errorf("migration 478 is not applied")
+ }
+ var compatible bool
+ if err := tx.QueryRow(ctx, `SELECT bool_and(issue_status_category(old_value)=new_value)
+ FROM (VALUES ('backlog','unstarted'),('todo','unstarted'),('in_progress','started'),
+ ('in_review','started'),('blocked','started'),('cancelled','closed'),
+ ('unstarted','unstarted'),('started','started'),('done','done'),('closed','closed')) v(old_value,new_value)`).Scan(&compatible); err != nil {
+ return err
+ }
+ if !compatible {
+ return fmt.Errorf("category mapping does not match processor version 1")
+ }
+ // Read actual CHECK definitions as well as the ledger: a recorded migration
+ // alone cannot prove that the compatibility schema is still installed.
+ for _, name := range []string{"issue_status_category_check", "issue_status_system_is_canonical"} {
+ var expression string
+ if err := tx.QueryRow(ctx, `SELECT pg_get_expr(conbin,conrelid) FROM pg_constraint
+ WHERE conrelid='issue_status'::regclass AND conname=$1 AND contype='c'`, name).Scan(&expression); err != nil {
+ return err
+ }
+ for _, value := range []string{"backlog", "todo", "in_progress", "in_review", "blocked", "cancelled", "unstarted", "started", "done", "closed"} {
+ if !strings.Contains(expression, "'"+value+"'") {
+ return fmt.Errorf("compatibility CHECK %s lacks %s", name, value)
+ }
+ }
+ }
+ var effective string
+ if err := tx.QueryRow(ctx, "SELECT pg_get_functiondef('issue_effective_status(uuid,text)'::regprocedure)").Scan(&effective); err != nil {
+ return err
+ }
+ if !strings.Contains(effective, "WHEN 'cancelled'") || !strings.Contains(effective, "WHEN 'closed'") {
+ return fmt.Errorf("issue_effective_status does not recognize both terminal spellings")
+ }
+ return nil
+}
+
+type statusCheckpoint struct {
+ Phase string `json:"phase"`
+ AfterID string `json:"after_id"`
+}
+type statusProgress struct {
+ Scanned int64 `json:"scanned"`
+ Updated int64 `json:"updated"`
+ WouldUpdate int64 `json:"would_update"`
+ Verified int64 `json:"verified"`
+ Archived int64 `json:"archived"`
+ System int64 `json:"system"`
+ Categories map[string]int64 `json:"categories"`
+}
+
+var categoryMapping = map[string]string{
+ "backlog": "unstarted", "todo": "unstarted", "in_progress": "started", "in_review": "started",
+ "blocked": "started", "cancelled": "closed", "unstarted": "unstarted", "started": "started", "done": "done", "closed": "closed",
+}
+var systemCategories = map[string]string{"backlog": "unstarted", "todo": "unstarted", "in_progress": "started", "in_review": "started", "blocked": "started", "done": "done", "cancelled": "closed"}
+
+func (StatusCategory) Step(ctx context.Context, tx pgx.Tx, j Job) (json.RawMessage, json.RawMessage, json.RawMessage, bool, error) {
+ var cp statusCheckpoint
+ var progress statusProgress
+ if err := decode(j.Checkpoint, &cp); err != nil {
+ return nil, nil, nil, false, err
+ }
+ if err := decode(j.Progress, &progress); err != nil {
+ return nil, nil, nil, false, err
+ }
+ if cp.Phase == "" {
+ cp.Phase = "scan"
+ }
+ if cp.Phase != "scan" && cp.Phase != "verify" {
+ return nil, nil, nil, false, fmt.Errorf("unknown checkpoint phase")
+ }
+ if progress.Categories == nil {
+ progress.Categories = map[string]int64{}
+ }
+ // Do not filter on category before LIMIT: even a mostly migrated table scans
+ // only one indexed page per request. Advance over examined, not updated, IDs.
+ query := "SELECT id::text,key,category,is_system,archived_at IS NOT NULL FROM issue_status"
+ args := []any{j.Options.BatchSize}
+ if cp.AfterID != "" {
+ query += " WHERE id > $2::uuid"
+ args = append(args, cp.AfterID)
+ }
+ // Qualify the UUID column: an unqualified ORDER BY id would resolve to the
+ // SELECT's id::text output and require a text sort instead of the UUID index.
+ query += " ORDER BY issue_status.id LIMIT $1"
+ rows, err := tx.Query(ctx, query, args...)
+ if err != nil {
+ return nil, nil, nil, false, err
+ }
+ var ids []string
+ for rows.Next() {
+ var id, key, category string
+ var system, archived bool
+ if err = rows.Scan(&id, &key, &category, &system, &archived); err != nil {
+ break
+ }
+ canonical, ok := categoryMapping[category]
+ if !ok {
+ err = fmt.Errorf("unknown category %q at status %s", category, id)
+ break
+ }
+ if system && (systemCategories[key] != canonical || (category != key && category != canonical)) {
+ err = fmt.Errorf("noncanonical system status %s", id)
+ break
+ }
+ if cp.Phase == "verify" {
+ if category != canonical {
+ err = fmt.Errorf("legacy category remains at status %s; investigate writers and start a new pass", id)
+ break
+ }
+ progress.Verified++
+ } else {
+ progress.Scanned++
+ progress.Categories[category]++
+ if category != canonical {
+ progress.WouldUpdate++
+ }
+ if system {
+ progress.System++
+ }
+ if archived {
+ progress.Archived++
+ }
+ }
+ ids = append(ids, id)
+ }
+ rowErr := rows.Err()
+ rows.Close()
+ if err != nil {
+ return nil, nil, nil, false, err
+ }
+ if rowErr != nil {
+ return nil, nil, nil, false, rowErr
+ }
+ if len(ids) > 0 {
+ if cp.Phase == "scan" && !j.DryRun {
+ tag, e := tx.Exec(ctx, `UPDATE issue_status SET category=issue_status_category(category)
+ WHERE id=ANY($1::uuid[]) AND category IN ('backlog','todo','in_progress','in_review','blocked','cancelled')`, ids)
+ if e != nil {
+ return nil, nil, nil, false, e
+ }
+ progress.Updated += tag.RowsAffected()
+ }
+ cp.AfterID = ids[len(ids)-1]
+ return asJSON(cp), asJSON(progress), j.Result, false, nil
+ }
+ if cp.Phase == "scan" && !j.DryRun {
+ cp = statusCheckpoint{Phase: "verify"}
+ return asJSON(cp), asJSON(progress), j.Result, false, nil
+ }
+ result := map[string]any{"dry_run": j.DryRun, "checked_at": time.Now().UTC(), "scanned": progress.Scanned,
+ "updated": progress.Updated, "would_update": progress.WouldUpdate, "verified": progress.Verified,
+ "invalid": 0, "writers_upgraded_is_operator_attestation": true}
+ if !j.DryRun {
+ result["remaining_legacy"] = 0
+ }
+ return asJSON(cp), asJSON(progress), asJSON(result), true, nil
+}
diff --git a/server/migrations/485_maintenance_job.down.sql b/server/migrations/485_maintenance_job.down.sql
new file mode 100644
index 0000000000..5393e8d6e1
--- /dev/null
+++ b/server/migrations/485_maintenance_job.down.sql
@@ -0,0 +1,2 @@
+-- Preserve resumable work and completion evidence on application rollback.
+SELECT 1;
diff --git a/server/migrations/485_maintenance_job.up.sql b/server/migrations/485_maintenance_job.up.sql
new file mode 100644
index 0000000000..8ddc16019d
--- /dev/null
+++ b/server/migrations/485_maintenance_job.up.sql
@@ -0,0 +1,25 @@
+-- Operator-driven maintenance only; creating this table starts no work.
+CREATE TABLE IF NOT EXISTS maintenance_job (
+ id UUID NOT NULL DEFAULT gen_random_uuid(),
+ job_type TEXT NOT NULL,
+ job_version INTEGER NOT NULL CHECK (job_version > 0),
+ scope_key TEXT NOT NULL,
+ idempotency_key TEXT NOT NULL,
+ request_hash TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('ready', 'paused', 'completed', 'cancelled')),
+ revision BIGINT NOT NULL DEFAULT 0,
+ dry_run BOOLEAN NOT NULL DEFAULT true,
+ options JSONB NOT NULL,
+ parameters JSONB NOT NULL DEFAULT '{}',
+ checkpoint JSONB NOT NULL DEFAULT '{}',
+ progress JSONB NOT NULL DEFAULT '{}',
+ result JSONB NOT NULL DEFAULT '{}',
+ last_error TEXT NOT NULL DEFAULT '',
+ next_allowed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ completed_at TIMESTAMPTZ,
+ CHECK (jsonb_typeof(options) = 'object' AND jsonb_typeof(parameters) = 'object'
+ AND jsonb_typeof(checkpoint) = 'object' AND jsonb_typeof(progress) = 'object'
+ AND jsonb_typeof(result) = 'object')
+);
diff --git a/server/migrations/486_maintenance_job_id_index.down.sql b/server/migrations/486_maintenance_job_id_index.down.sql
new file mode 100644
index 0000000000..59954e1006
--- /dev/null
+++ b/server/migrations/486_maintenance_job_id_index.down.sql
@@ -0,0 +1,2 @@
+-- Retain maintenance state and its concurrency guards on application rollback.
+SELECT 1;
diff --git a/server/migrations/486_maintenance_job_id_index.up.sql b/server/migrations/486_maintenance_job_id_index.up.sql
new file mode 100644
index 0000000000..07d7257ede
--- /dev/null
+++ b/server/migrations/486_maintenance_job_id_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_maintenance_job_id ON maintenance_job (id);
diff --git a/server/migrations/487_maintenance_job_idempotency_index.down.sql b/server/migrations/487_maintenance_job_idempotency_index.down.sql
new file mode 100644
index 0000000000..59954e1006
--- /dev/null
+++ b/server/migrations/487_maintenance_job_idempotency_index.down.sql
@@ -0,0 +1,2 @@
+-- Retain maintenance state and its concurrency guards on application rollback.
+SELECT 1;
diff --git a/server/migrations/487_maintenance_job_idempotency_index.up.sql b/server/migrations/487_maintenance_job_idempotency_index.up.sql
new file mode 100644
index 0000000000..1fafc10158
--- /dev/null
+++ b/server/migrations/487_maintenance_job_idempotency_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_maintenance_job_idempotency ON maintenance_job (idempotency_key);
diff --git a/server/migrations/488_maintenance_job_active_index.down.sql b/server/migrations/488_maintenance_job_active_index.down.sql
new file mode 100644
index 0000000000..59954e1006
--- /dev/null
+++ b/server/migrations/488_maintenance_job_active_index.down.sql
@@ -0,0 +1,2 @@
+-- Retain maintenance state and its concurrency guards on application rollback.
+SELECT 1;
diff --git a/server/migrations/488_maintenance_job_active_index.up.sql b/server/migrations/488_maintenance_job_active_index.up.sql
new file mode 100644
index 0000000000..0c129513da
--- /dev/null
+++ b/server/migrations/488_maintenance_job_active_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_maintenance_job_active ON maintenance_job (job_type, scope_key) WHERE status IN ('ready', 'paused');
diff --git a/server/pkg/agent/cursor_liveness_test.go b/server/pkg/agent/cursor_liveness_test.go
index 25c315431e..1ebc0e6690 100644
--- a/server/pkg/agent/cursor_liveness_test.go
+++ b/server/pkg/agent/cursor_liveness_test.go
@@ -174,7 +174,22 @@ func runFakeCursorStream(mode string) {
}
fmt.Println(`{"type":"thinking","subtype":"delta","text":"ready"}`)
fmt.Println(`{"type":"thinking","subtype":"completed"}`)
- if mode != "finish" {
+ if mode == "finish" {
+ // Finalization tests an already-owned background shell. Keep the fake
+ // CLI alive until the consumer has processed the launch event; exiting
+ // here first reparents the shell and correctly fails ancestry validation.
+ gate := filepath.Join(os.Getenv("CURSOR_FAKE_DIR"), "finish.release")
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ if _, err := os.Stat(gate); err == nil {
+ break
+ }
+ if time.Now().After(deadline) {
+ panic("test consumer did not acknowledge background ownership")
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ } else {
for _, child := range children {
_ = child.Wait()
}
@@ -254,6 +269,16 @@ func TestCursorBackgroundLifecycle(t *testing.T) {
t.Fatal("fake never reached background observation")
}
switch mode {
+ case "finish":
+ // The ready message follows synchronous ownership capture. A
+ // rejected launch has already released its tool count, so this
+ // also proves that finalization will exercise owned-process cleanup.
+ if count, _ := session.ToolActivity(); count != 1 {
+ t.Fatalf("background shell was not retained before finalization: count=%d", count)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "finish.release"), nil, 0600); err != nil {
+ t.Fatal(err)
+ }
case "budget", "multiple":
if !session.InterruptBackgroundTools() {
t.Fatal("tool budget did not clean up owned background processes")
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 330a7cd833..c38403e464 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -1032,6 +1032,28 @@ type LarkUserBinding struct {
BoundAt pgtype.Timestamptz `json:"bound_at"`
}
+type MaintenanceJob struct {
+ ID pgtype.UUID `json:"id"`
+ JobType string `json:"job_type"`
+ JobVersion int32 `json:"job_version"`
+ ScopeKey string `json:"scope_key"`
+ IdempotencyKey string `json:"idempotency_key"`
+ RequestHash string `json:"request_hash"`
+ Status string `json:"status"`
+ Revision int64 `json:"revision"`
+ DryRun bool `json:"dry_run"`
+ Options []byte `json:"options"`
+ Parameters []byte `json:"parameters"`
+ Checkpoint []byte `json:"checkpoint"`
+ Progress []byte `json:"progress"`
+ Result []byte `json:"result"`
+ LastError string `json:"last_error"`
+ NextAllowedAt pgtype.Timestamptz `json:"next_allowed_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ CompletedAt pgtype.Timestamptz `json:"completed_at"`
+}
+
type Member struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`