Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ All notable changes to this project are documented here. The format is based on
- Source PRs now receive explicit terminal queue feedback: landed, rejected,
skipped/requeued, and merge-error outcomes include commit statuses, durable
comments, and staging debug links when available.
- Optional bbolt queue checkpoint storage via `SHUNT_STATE_PATH`, preserving
pending candidates, active batch metadata, linger state, and bisection counters
across restarts; restored active batches are re-staged before landing.

### Fixed
- Forgejo Actions readiness now prefers the run-level aggregate status before
Expand Down
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ is discovered and managed automatically. For a single repo, set
| `SHUNT_BATCH_TARGET` | `0` | Start a lingering batch early once this many ready PRs are present (0 = wait the full linger window). |
| `SHUNT_BISECT_FANOUT` | `1` | Maximum concurrent bisection staging runs per queue. `1` preserves serial bisection. |
| `SHUNT_QUEUE_COMMENTS` | `false` | When true, maintain one sticky queue-status comment on each queued PR. Disabled by default to avoid extra write traffic. |
| `SHUNT_STATE_PATH` | — | Optional path to a local bbolt database for durable queue checkpoints. Leave empty for in-memory state. |
| `SHUNT_POLL_INTERVAL` | `10s` | Reconcile cadence |
| `SHUNT_PUBLIC_URL` | = `SHUNT_INSTANCE` | Base URL for the links written into PR comments (set when the bot reaches the forge over an internal URL) |
| `SHUNT_LISTEN` | `:8080` | Address for the `/healthz`, `/metrics`, and `/webhook` endpoints |
Expand All @@ -127,6 +128,14 @@ choosing the managed base; in single-repo mode, it reads from `SHUNT_BASE`.
Missing files keep the global defaults. Invalid files are logged/rejected without
applying partial settings.

Set `SHUNT_STATE_PATH` to persist queue checkpoints in a local bbolt database.
This is the default built-in durable store. It keeps shunt's static, CGO-free
binary while preserving pending candidates, active batch metadata, linger state,
and bisection counters across restarts. Active batches are re-staged after
restore rather than landed from pre-restart CI results. In Kubernetes, mount the
path on a persistent volume; an `emptyDir` path only survives container restarts
within the same pod lifetime.

```yaml
base: trunk
status_context: shunt
Expand Down Expand Up @@ -218,8 +227,8 @@ If `/webhook` is exposed beyond a trusted private network, set

## Status & roadmap

v0.3 is functional but young. Known limitations (in-memory state, polling as a
webhook backstop, single replica) and the plan to address them are tracked in
v0.3 is functional but young. Known limitations (opt-in durable state, polling
as a webhook backstop, single replica) and the plan to address them are tracked in
[`ROADMAP.md`](ROADMAP.md).

## License
Expand Down
20 changes: 12 additions & 8 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ welcome.

## Current limitations

- **In-memory state.** The queue and the bisection frontier live in memory. A
restart never double-merges or loses a PR (it re-derives the queue from the
open auto-merge PRs), but it forgets an in-flight bisection and re-runs that
CI. A crash mid-landing merges part of a batch and re-queues the rest next
cycle.
- **Durable state is opt-in.** By default, shunt still runs with in-memory state.
Set `SHUNT_STATE_PATH` to enable the built-in bbolt checkpoint store so pending
candidates, active batch metadata, linger state, and bisection counters survive
restarts. Restored active batches are re-staged before landing. A crash
mid-landing can still merge part of a batch and re-queue the rest next cycle.
- **Polling backstop.** shunt still reconciles on a timer (default 10s) to
tolerate missed webhooks, so there is some steady API traffic even when webhook
wakeups are configured.
Expand All @@ -68,9 +68,13 @@ welcome.
## Milestones

### v0.3 — Durability
- Postgres-backed state: persist the per-`(repo, base)` work queue, the active
batch (staging branch/SHA, members), and the bisection frontier; resume
cleanly across restarts.
- ~~Engine checkpoint/resume boundary and default local store: load and save the
per-`(repo, base)` work queue, active batch metadata, linger timestamp, and
bisection counters through a pluggable store.~~ Completed with an opt-in bbolt
implementation via `SHUNT_STATE_PATH`; restored active batches are re-staged
on restart.
- External durable stores: adapt the checkpoint boundary to Postgres or other
deployment-specific backends without changing the engine state machine.
- ~~Webhooks: react to `auto_merge_pull_request` (and `push`) to wake reconcile
immediately, keeping the poll as a backstop.~~ Completed: `/webhook` wakes the
reconcile loop for auto-merge, pull-request, review, status, and push events
Expand Down
13 changes: 13 additions & 0 deletions charts/shunt/templates/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ spec:
value: {{ .Values.config.bisectFanout | quote }}
- name: SHUNT_QUEUE_COMMENTS
value: {{ .Values.config.queueComments | quote }}
{{- if .Values.config.statePath }}
- name: SHUNT_STATE_PATH
value: {{ .Values.config.statePath | quote }}
{{- end }}
- name: SHUNT_POLL_INTERVAL
value: {{ .Values.config.pollInterval | quote }}
{{- if .Values.config.publicUrl }}
Expand Down Expand Up @@ -108,9 +112,18 @@ spec:
volumeMounts:
- name: tmp
mountPath: /tmp
{{- if .Values.persistence.enabled }}
- name: state
mountPath: /var/lib/shunt
{{- end }}
volumes:
- name: tmp
emptyDir: {}
{{- if .Values.persistence.enabled }}
- name: state
persistentVolumeClaim:
claimName: {{ default (printf "%s-state" (include "shunt.fullname" .)) .Values.persistence.existingClaim | quote }}
{{- end }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
Expand Down
17 changes: 17 additions & 0 deletions charts/shunt/templates/pvc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{{- if and .Values.persistence.enabled (not .Values.persistence.existingClaim) }}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: {{ include "shunt.fullname" . }}-state
labels:
{{- include "shunt.labels" . | nindent 4 }}
spec:
accessModes:
{{- toYaml .Values.persistence.accessModes | nindent 4 }}
resources:
requests:
storage: {{ .Values.persistence.size | quote }}
{{- if .Values.persistence.storageClassName }}
storageClassName: {{ .Values.persistence.storageClassName | quote }}
{{- end }}
{{- end }}
9 changes: 9 additions & 0 deletions charts/shunt/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ config:
batchTarget: "0"
bisectFanout: "1"
queueComments: "false"
statePath: ""
pollInterval: "10s"
listen: ":8080"
webhookUrl: ""
Expand All @@ -36,6 +37,14 @@ webhookSecret:
existingSecret: ""
key: webhook-secret

persistence:
enabled: false
existingClaim: ""
size: 1Gi
storageClassName: ""
accessModes:
- ReadWriteOnce

podAnnotations: {}

podSecurityContext:
Expand Down
25 changes: 23 additions & 2 deletions cmd/shunt/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"strings"
"time"

checkpointbolt "github.com/rbtr/shunt/internal/checkpoint/bolt"
"github.com/rbtr/shunt/internal/engine"
"github.com/rbtr/shunt/internal/forge"
"github.com/rbtr/shunt/internal/gitops"
Expand Down Expand Up @@ -89,6 +90,13 @@ func main() {
}

metricsCollector := metrics.New()
checkpointStore, err := openCheckpointStore()
if err != nil {
log.Fatal(err)
}
if checkpointStore != nil {
defer checkpointStore.Close()
}
wake := make(chan struct{}, 1)
go serveHealth(env("SHUNT_LISTEN", ":8080"), metricsCollector, webhookConfig{
Secret: webhookSecret,
Expand All @@ -102,7 +110,7 @@ func main() {
Topic: topic, StatusCtx: statusCtx, MergeStyle: mergeStyle, MaxBatch: maxBatch, BatchLinger: batchLinger, BatchTarget: batchTarget, BisectFanout: bisectFanout, QueueComments: queueComments,
WebhookURL: webhookURL, WebhookSecret: webhookSecret,
InstanceURL: instance, PublicURL: publicURL, Token: token, BotUser: botUser, BotEmail: botEmail,
Metrics: metricsCollector,
Metrics: metricsCollector, Checkpoint: checkpointStore,
})
log.Printf("shunt: multi-repo mode, topic=%q every %s", topic, interval)
runReconcileLoop(interval, wake, func() {
Expand Down Expand Up @@ -146,7 +154,7 @@ func main() {
Owner: owner, Repo: repo, Base: base,
StatusCtx: settings.StatusCtx, MergeStyle: settings.MergeStyle, MaxBatch: settings.MaxBatch, BatchLinger: settings.BatchLinger, BatchTarget: settings.BatchTarget, BisectFanout: settings.BisectFanout, QueueComments: queueComments, BotUser: botUser,
StagingBranch: "mq/" + base + "/staging", InstanceURL: instance, PublicURL: publicURL,
Metrics: metricsCollector,
Metrics: metricsCollector, Checkpoint: checkpointStore,
}, fc, gitops.NewStager(cloneURL, botUser, token, botUser, botEmail))
log.Printf("shunt: watching %s/%s base=%s every %s", owner, repo, base, interval)
runReconcileLoop(interval, wake, func() {
Expand All @@ -156,6 +164,19 @@ func main() {
})
}

func openCheckpointStore() (*checkpointbolt.Store, error) {
path := strings.TrimSpace(os.Getenv("SHUNT_STATE_PATH"))
if path == "" {
return nil, nil
}
store, err := checkpointbolt.Open(path)
if err != nil {
return nil, fmt.Errorf("open SHUNT_STATE_PATH: %w", err)
}
log.Printf("shunt: using bbolt queue state at %s", path)
return store, nil
}

func serveHealth(addr string, metricsCollector *metrics.Collector, webhook webhookConfig) {
if err := http.ListenAndServe(addr, newHTTPMux(metricsCollector, webhook)); err != nil {
log.Printf("health server: %v", err)
Expand Down
25 changes: 25 additions & 0 deletions cmd/shunt/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,28 @@ func TestEnvBool(t *testing.T) {
t.Fatal("envBool should reject invalid values")
}
}

func TestOpenCheckpointStoreDisabledByDefault(t *testing.T) {
t.Setenv("SHUNT_STATE_PATH", "")
store, err := openCheckpointStore()
if err != nil {
t.Fatalf("open checkpoint store: %v", err)
}
if store != nil {
t.Fatal("store = non-nil, want nil when SHUNT_STATE_PATH is unset")
}
}

func TestOpenCheckpointStoreUsesStatePath(t *testing.T) {
t.Setenv("SHUNT_STATE_PATH", t.TempDir()+"/shunt.db")
store, err := openCheckpointStore()
if err != nil {
t.Fatalf("open checkpoint store: %v", err)
}
if store == nil {
t.Fatal("store = nil, want bbolt store")
}
if err := store.Close(); err != nil {
t.Fatalf("close store: %v", err)
}
}
8 changes: 8 additions & 0 deletions deploy/kustomize/base/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ spec:
value: "1"
- name: SHUNT_QUEUE_COMMENTS
value: "false"
# Set this to a mounted persistent path to enable bbolt checkpoints.
# - name: SHUNT_STATE_PATH
# value: "/var/lib/shunt/shunt.db"
# Set this to the public /webhook URL to let shunt create repo webhooks.
# - name: SHUNT_WEBHOOK_URL
# value: "https://shunt.example.com/webhook"
Expand Down Expand Up @@ -69,6 +72,11 @@ spec:
volumeMounts:
- name: tmp
mountPath: /tmp
# - name: state
# mountPath: /var/lib/shunt
volumes:
- name: tmp
emptyDir: {}
# - name: state
# persistentVolumeClaim:
# claimName: shunt-state
27 changes: 24 additions & 3 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ State, per `(repo, base)`:
- `lingerSince` — when the idle engine first saw ready PRs while the optional
batch-accumulation window was active.

The engine has a checkpoint boundary around that state: when configured with its
consumer-side `CheckpointStore`, it loads one queue snapshot before the first
reconcile tick, saves after each tick that leaves queue work in progress, and
deletes the snapshot once the queue is idle. The production command wires the
default bbolt store when `SHUNT_STATE_PATH` is set; otherwise releases keep the
historical process-local state.

Each `Reconcile()` tick advances one step. Ticks are driven by relevant
Forgejo/Gitea webhooks when available, with `SHUNT_POLL_INTERVAL` as the
backstop so a missed webhook only delays progress:
Expand Down Expand Up @@ -136,6 +143,17 @@ from the *current* base tip, a successful sub-batch that advances the base is
handled safely: any later speculative staging run from the old base generation is
deleted and re-queued, then re-staged before it can land.

The neutral `checkpoint` package defines the snapshot DTOs. The engine owns the
consumer-side store interface, and the concrete bbolt implementation lives in
the more specific `checkpoint/bolt` package. Restored active batches are
conservatively re-queued for fresh staging instead of resuming an old staging
branch/run, so startup staging-branch cleanup cannot delete a branch that the
restored engine still expects to observe. The production command wires the
default bbolt implementation when `SHUNT_STATE_PATH` is set. That store persists
one snapshot per `(owner, repo, base)` and keeps the binary static/CGO-free;
operators should place the database on persistent storage if they want queue
state to survive pod replacement or host reboots.

### Worked example

Four ready PRs `[1 2 3 4]`, where `3` is broken:
Expand Down Expand Up @@ -192,9 +210,12 @@ against the unchanged current base, so `2` can still pass.
repository; squash-only repositories need `SHUNT_MERGE_STYLE=squash`. Keep
"block on outdated branch" disabled so the queue, not per-PR freshness checks,
decides when a tested PR can land.
- **Crash safety (today).** State is in-memory; a restart re-derives the queue
from open auto-merge PRs. It may repeat a staging run, but never double-merges
and never loses a PR. Durable state is a roadmap item.
- **Crash safety.** By default, state is still in-memory; a restart re-derives
the queue from open auto-merge PRs. It may repeat a staging run, but never
double-merges and never loses a PR. With `SHUNT_STATE_PATH`, shunt persists the
pending frontier, linger state, bisection counters, and active batch metadata
in bbolt. Active batches are re-staged after restore so no PR lands from a
pre-restart staging result that may have been invalidated by a base change.

## Observability

Expand Down
1 change: 1 addition & 0 deletions examples/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ SHUNT_TOPIC=merge-queue
# SHUNT_BATCH_TARGET=0
# SHUNT_BISECT_FANOUT=1
# SHUNT_QUEUE_COMMENTS=false # set true for sticky PR queue-status comments
# SHUNT_STATE_PATH= # optional local bbolt checkpoint DB, e.g. /var/lib/shunt/shunt.db
# SHUNT_POLL_INTERVAL=10s
# SHUNT_LISTEN=:8080
# SHUNT_WEBHOOK_URL=https://shunt.example.com/webhook # set to let shunt configure repo webhooks
Expand Down
9 changes: 9 additions & 0 deletions examples/kubernetes.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ spec:
value: "merge-queue"
- name: SHUNT_QUEUE_COMMENTS
value: "false"
# Optional durable bbolt checkpoints. Mount this path on persistent
# storage; emptyDir only survives restarts within the same pod.
# - name: SHUNT_STATE_PATH
# value: "/var/lib/shunt/shunt.db"
# Set this to the public /webhook URL to let shunt create repo webhooks.
# - name: SHUNT_WEBHOOK_URL
# value: "https://shunt.example.com/webhook"
Expand Down Expand Up @@ -78,6 +82,11 @@ spec:
volumeMounts:
- name: tmp
mountPath: /tmp
# - name: state
# mountPath: /var/lib/shunt
volumes:
- name: tmp
emptyDir: {}
# - name: state
# persistentVolumeClaim:
# claimName: shunt-state
7 changes: 6 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,9 @@ module github.com/rbtr/shunt

go 1.23

require gopkg.in/yaml.v3 v3.0.1
require (
go.etcd.io/bbolt v1.3.11
gopkg.in/yaml.v3 v3.0.1
)

require golang.org/x/sys v0.30.0 // indirect
12 changes: 12 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
go.etcd.io/bbolt v1.3.11 h1:yGEzV1wPz2yVCLsD8ZAiGHhHVlczyC9d1rP43/VCRJ0=
go.etcd.io/bbolt v1.3.11/go.mod h1:dksAq7YMXoljX0xu6VF5DMZGbhYYoLUalEiSySYAS4I=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
Expand Down
Loading
Loading