test(pipeline): verify idempotency under faults and reordered delivery

This commit is contained in:
kk10
2026-11-16 22:51:35 +03:00
parent f8ca7a7218
commit 179c795758
6 changed files with 383 additions and 201 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build contract || reconcile || failure || worker
//go:build contract || reconcile || failure || worker || pipeline
package studenttests_test
+78 -1
View File
@@ -1,12 +1,19 @@
//go:build failure || worker
//go:build failure || worker || pipeline
package studenttests_test
import (
"context"
"io"
"net/http"
"os/exec"
"strings"
"testing"
"time"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
)
func compose(t *testing.T, args ...string) {
@@ -45,3 +52,73 @@ func waitReady(t *testing.T) {
}
t.Fatal("service did not become ready in 60s")
}
func workerCommand(t *testing.T, args ...string) string {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "docker", args...)
cmd.Dir = ".."
out, err := cmd.Output()
if err != nil {
t.Fatalf("Docker command failed: %v", err)
}
return strings.TrimSpace(string(out))
}
func workerSQL(t *testing.T, query string) string {
t.Helper()
return workerCommand(t, "compose", "exec", "-T", "postgres", "psql",
"-U", "messenger", "-d", "messenger", "-Atqc", query)
}
func workerWait(t *testing.T, description string, timeout time.Duration, condition func() bool) {
t.Helper()
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
if condition() {
return
}
time.Sleep(300 * time.Millisecond)
}
t.Fatalf("timeout waiting for %s", description)
}
func workerQueue(t *testing.T) string {
t.Helper()
out := workerCommand(t, "compose", "exec", "-T", "rabbitmq", "rabbitmqctl",
"list_queues", "name", "messages_ready", "messages_unacknowledged", "--silent")
for _, line := range strings.Split(out, "\n") {
fields := strings.Fields(line)
if len(fields) == 3 && fields[0] == "attachments.process.v1" {
return fields[1] + ":" + fields[2]
}
}
t.Fatal("attachment queue missing")
return ""
}
func workerUpload(t *testing.T, user testUser, chatID uuid.UUID) (dto.AttachmentResponse, []byte) {
t.Helper()
source := makePNG(t, 320, 200)
resp := uploadAttachment(t, user, chatID, "worker.png", "image/png", source)
requireStatus(t, resp, http.StatusAccepted)
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
if att.Status != "queued" {
t.Fatalf("expected queued, got %s", att.Status)
}
return att, source
}
func workerContent(t *testing.T, user testUser, id uuid.UUID, variant string) []byte {
t.Helper()
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+id.String()+"/content?variant="+variant, user.Token, nil)
requireStatus(t, resp, http.StatusOK)
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
return data
}
-126
View File
@@ -1,126 +0,0 @@
//go:build pipeline
package studenttests_test
import (
"bytes"
"context"
"encoding/gob"
"image"
"image/color"
"image/jpeg"
"image/png"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
"golang.org/x/image/webp"
)
func TestPipelineImageVersions(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
binary := filepath.Join(t.TempDir(), "worker")
build := exec.CommandContext(ctx, "go", "build", "-tags=nodynamic", "-o", binary, "../cmd/worker")
if out, err := build.CombinedOutput(); err != nil {
t.Fatalf("build worker: %v\n%s", err, out)
}
src := image.NewNRGBA(image.Rect(0, 0, 320, 200))
for y := 0; y < 200; y++ {
for x := 0; x < 320; x++ {
src.SetNRGBA(x, y, color.NRGBA{
R: uint8(x*17 + y*3),
G: uint8(x*5 + y*11),
B: uint8(x * y), A: 255,
})
}
}
var source bytes.Buffer
if err := png.Encode(&source, src); err != nil {
t.Fatal(err)
}
sourcePath := filepath.Join(t.TempDir(), "source.png")
if err := os.WriteFile(sourcePath, source.Bytes(), 0600); err != nil {
t.Fatal(err)
}
// Decode the child process protocol without exporting worker internals.
type variant struct {
Name, ContentType string
Data []byte
Width, Height int
}
process := func(version string) []variant {
t.Helper()
args := []string{"-process-image", "40000000"}
if version != "" {
args = append(args, "-pipeline-version", version)
}
cmd := exec.CommandContext(ctx, binary, args...)
input, err := os.Open(sourcePath)
if err != nil {
t.Fatal(err)
}
defer input.Close()
cmd.Stdin = input
var stderr bytes.Buffer
cmd.Stderr = &stderr
out, err := cmd.Output()
if err != nil {
t.Fatalf("process v%s: %v: %s", version, err, stderr.String())
}
var variants []variant
if err := gob.NewDecoder(bytes.NewReader(out)).Decode(&variants); err != nil {
t.Fatal(err)
}
if len(variants) != 3 {
t.Fatalf("expected three variants, got %d", len(variants))
}
for i, name := range []string{"thumbnail", "crop", "optimized"} {
v := variants[i]
var cfg image.Config
var err error
width, height, contentType := 256, 160, "image/jpeg"
if name == "optimized" {
width, height, contentType = 320, 200, "image/webp"
cfg, err = webp.DecodeConfig(bytes.NewReader(v.Data))
} else {
if name == "crop" {
width, height = 128, 128
}
cfg, err = jpeg.DecodeConfig(bytes.NewReader(v.Data))
}
if err != nil || v.Name != name || v.ContentType != contentType ||
v.Width != width || v.Height != height || cfg.Width != width || cfg.Height != height {
t.Fatalf("invalid v%s %s: metadata=%dx%d, decoded=%dx%d, error=%v",
version, name, v.Width, v.Height, cfg.Width, cfg.Height, err)
}
}
return variants
}
v1, v2 := process("1"), process("2")
defaultVersion := process("")
for i := range v1 {
if !bytes.Equal(v1[i].Data, defaultVersion[i].Data) {
t.Fatal("default processing differs from v1")
}
wantEqual := v1[i].Name != "optimized"
if bytes.Equal(v1[i].Data, v2[i].Data) != wantEqual {
t.Fatalf("expected only optimized bytes to differ: %s", v1[i].Name)
}
}
cmd := exec.CommandContext(ctx, binary, "-process-image", "40000000", "-pipeline-version", "3")
cmd.Stdin = bytes.NewReader(source.Bytes())
if out, err := cmd.Output(); err == nil || len(out) != 0 {
t.Fatal("unsupported version must fail without a result")
}
}
+302
View File
@@ -0,0 +1,302 @@
//go:build pipeline
package studenttests_test
import (
"bytes"
"encoding/base64"
"reflect"
"testing"
"time"
"github.com/google/uuid"
"golang.org/x/image/webp"
)
func pipelineS3Gate(t *testing.T, suffix string) (string, func(string) string) {
t.Helper()
proxy := "pipeline-gate-" + uuid.NewString()
workerContainer := workerCommand(t, "compose", "ps", "-a", "-q", "worker")
network := workerCommand(t, "inspect", "--format",
"{{range $name, $value := .NetworkSettings.Networks}}{{$name}}{{end}}", workerContainer)
t.Cleanup(func() { workerCommand(t, "rm", "-f", proxy) })
const proxyScript = `
import base64
import http.client
import http.server
import threading
import sys
waiting = threading.Event()
release = threading.Event()
written = threading.Event()
held_body = b''
class Proxy(http.server.BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
if self.path == '/_body':
self.send_response(200)
self.end_headers()
self.wfile.write(base64.b64encode(held_body))
return
if self.path == '/_state':
data = f'{int(waiting.is_set())}:{int(written.is_set())}'.encode()
self.send_response(200)
self.end_headers()
self.wfile.write(data)
return
if self.path == '/_release':
release.set()
self.send_response(200)
self.end_headers()
return
self.forward()
def do_PUT(self):
self.forward()
def forward(self):
global held_body
body = self.rfile.read(int(self.headers.get('Content-Length', 0)))
gated = self.command == 'PUT' and self.path.split('?')[0].endswith(sys.argv[1])
if gated:
held_body = body
waiting.set()
if not release.wait(90):
self.send_error(504)
return
conn = http.client.HTTPConnection('s3', 9000, timeout=20)
try:
conn.request(self.command, self.path, body, dict(self.headers))
response = conn.getresponse()
data = response.read()
if gated and response.status == 200:
written.set()
self.send_response(response.status)
for name, value in response.getheaders():
if name.lower() not in ('connection', 'transfer-encoding', 'content-length'):
self.send_header(name, value)
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
finally:
conn.close()
http.server.ThreadingHTTPServer(('0.0.0.0', 9000), Proxy).serve_forever()
`
workerCommand(t, "run", "-d", "--name", proxy, "--network", network,
"python:3.13.9-alpine3.22", "python", "-u", "-c", proxyScript, suffix)
control := func(path string) string {
t.Helper()
return workerCommand(t, "exec", proxy, "python", "-c",
"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:9000/"+path+"').read().decode())")
}
return proxy, control
}
func TestPipelineStaleProcessing(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
stopService(t, "worker")
if workerQueue(t) != "0:0" {
t.Fatal("run on an idle stand with an empty attachment queue")
}
att, source := workerUpload(t, user, chat.ID)
id := att.ID.String()
where := "attachment_id='" + id + "'"
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
// Hold the last v1 PUT while v2 completes, without a DB row lock.
proxy, control := pipelineS3Gate(t, "/v1/optimized")
oldWorker := "pipeline-v1-" + uuid.NewString()
t.Cleanup(func() { workerCommand(t, "rm", "-f", oldWorker) })
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", oldWorker,
"-e", "WORKER_CONCURRENCY=1", "-e", "JOB_TIMEOUT_SECONDS=120",
"-e", "S3_ENDPOINT=http://"+proxy+":9000", "worker")
workerWait(t, "v1 waiting before optimized PUT", 20*time.Second, func() bool {
return control("_state") == "1:0"
})
if workerSQL(t, "SELECT pipeline_version||':'||status||':'||attempts FROM attachments WHERE id='"+id+"'") != "1:processing:1" {
t.Fatal("v1 was not processing before upgrade")
}
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
compose(t, "start", "worker")
ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second)
if len(ready.Variants) != 3 ||
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" {
t.Fatal("v2 did not become ready while v1 was held")
}
content := make(map[string][]byte)
for _, name := range []string{"original", "thumbnail", "crop", "optimized"} {
content[name] = workerContent(t, user, att.ID, name)
}
if !bytes.Equal(content["original"], source) {
t.Fatal("v2 changed original bytes")
}
v1, err := base64.StdEncoding.DecodeString(control("_body"))
if err != nil {
t.Fatal(err)
}
for _, data := range [][]byte{v1, content["optimized"]} {
cfg, err := webp.DecodeConfig(bytes.NewReader(data))
if err != nil || cfg.Width != 320 || cfg.Height != 200 {
t.Fatal("expected valid optimized WebP from both versions")
}
}
if bytes.Equal(v1, content["optimized"]) {
t.Fatal("fixture must produce different v1 and v2 optimized bytes")
}
control("_release")
workerWait(t, "late v1 S3 write", 20*time.Second, func() bool {
return control("_state") == "1:1"
})
workerWait(t, "stale v1 redelivery acknowledged", 15*time.Second, func() bool {
return workerQueue(t) == "0:0"
})
after := waitAttachment(t, user, att.ID, "ready", 5*time.Second)
if !reflect.DeepEqual(ready, after) ||
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=1") != "0" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" {
t.Fatal("late v1 processing changed current metadata")
}
for name, before := range content {
if !bytes.Equal(before, workerContent(t, user, att.ID, name)) {
t.Fatalf("late v1 processing overwrote %s", name)
}
}
t.Logf("PASS attachment=%s: held v1 PUT; v2 ready; late v1 wrote S3 but could not replace v2; stale redelivery acknowledged", id)
}
func TestPipelineReorderAndDuplicate(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
stopService(t, "worker")
if workerQueue(t) != "0:0" {
t.Fatal("run on an idle stand with an empty attachment queue")
}
// Keep v1 durable in outbox, but delay its publication until v2 is ready.
stopService(t, "rabbitmq")
att, source := workerUpload(t, user, chat.ID)
id := att.ID.String()
where := "attachment_id='" + id + "'"
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
workerSQL(t, "UPDATE outbox SET available_at=now()+interval '1 hour' WHERE "+where)
if workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND published_at IS NULL") != "1" {
t.Fatal("v1 was published before the reorder injection")
}
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
compose(t, "start", "rabbitmq", "worker")
ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second)
workerWait(t, "v2 acknowledgement", 15*time.Second, func() bool {
return workerQueue(t) == "0:0"
})
if len(ready.Variants) != 3 ||
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:1" ||
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND pipeline_version=1 AND published_at IS NULL") != "1" {
t.Fatal("v2 did not finish before v1 publication")
}
content := make(map[string][]byte)
for _, name := range []string{"original", "thumbnail", "crop", "optimized"} {
content[name] = workerContent(t, user, att.ID, name)
}
if !bytes.Equal(content["original"], source) {
t.Fatal("v2 changed original bytes")
}
for _, injection := range []struct {
name, query, version string
}{
{"reordered v1", "UPDATE outbox SET available_at=now() WHERE " + where + " AND pipeline_version=1", "1"},
{"duplicate v2", "UPDATE outbox SET published_at=NULL WHERE " + where + " AND pipeline_version=2", "2"},
} {
compose(t, "stop", "worker")
workerSQL(t, injection.query)
workerWait(t, injection.name+" published", 15*time.Second, func() bool {
return workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+
" AND pipeline_version="+injection.version+" AND published_at IS NOT NULL") == "1" &&
workerQueue(t) == "1:0"
})
compose(t, "start", "worker")
workerWait(t, injection.name+" acknowledged", 15*time.Second, func() bool {
return workerQueue(t) == "0:0"
})
after := waitAttachment(t, user, att.ID, "ready", 5*time.Second)
if !reflect.DeepEqual(ready, after) ||
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:1" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=1") != "0" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" ||
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "2" {
t.Fatalf("%s changed metadata or created extra work", injection.name)
}
for name, before := range content {
if !bytes.Equal(before, workerContent(t, user, att.ID, name)) {
t.Fatalf("%s changed %s bytes", injection.name, name)
}
}
}
t.Logf("PASS attachment=%s: v2 completed before v1 delivery; stale v1 and duplicate v2 acknowledged without changes", id)
}
func TestPipelineCrashBeforeWrite(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
stopService(t, "worker")
if workerQueue(t) != "0:0" {
t.Fatal("run on an idle stand with an empty attachment queue")
}
att, source := workerUpload(t, user, chat.ID)
id := att.ID.String()
where := "attachment_id='" + id + "'"
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
// Original is the first result PUT. Neither it nor any variant reaches S3.
proxy, control := pipelineS3Gate(t, "/attachments/"+id)
testWorker := "pipeline-crash-" + uuid.NewString()
t.Cleanup(func() { workerCommand(t, "rm", "-f", testWorker) })
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker,
"-e", "WORKER_CONCURRENCY=1", "-e", "JOB_TIMEOUT_SECONDS=15",
"-e", "S3_ENDPOINT=http://"+proxy+":9000", "worker")
workerWait(t, "v2 held before first result PUT", 10*time.Second, func() bool {
return control("_state") == "1:0"
})
if workerSQL(t, "SELECT pipeline_version||':'||status||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:processing:1" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "0" {
t.Fatal("expected v2 processing without a committed result")
}
workerCommand(t, "kill", "--signal", "SIGKILL", testWorker)
// Kill the held request too: it must never be forwarded after the crash.
workerCommand(t, "kill", "--signal", "SIGKILL", proxy)
workerWait(t, "crashed v2 job returned to broker", 10*time.Second, func() bool {
return workerQueue(t) == "1:0"
})
compose(t, "start", "worker")
// Recovery must use the natural lease expiry; no status/lease SQL injection.
ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second)
workerWait(t, "recovered v2 acknowledgement", 15*time.Second, func() bool {
return workerQueue(t) == "0:0"
})
if len(ready.Variants) != 3 ||
!bytes.Equal(workerContent(t, user, att.ID, "original"), source) ||
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" ||
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "3" ||
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND pipeline_version=2 AND attempt=2 AND published_at IS NOT NULL") != "1" {
t.Fatal("crash recovery lost the accepted job or changed its identity or result")
}
for _, name := range []string{"thumbnail", "crop", "optimized"} {
if len(workerContent(t, user, att.ID, name)) == 0 {
t.Fatalf("recovered v2 has empty %s", name)
}
}
t.Logf("PASS attachment=%s: SIGKILL before first result PUT; natural lease recovery; same job ready on v2 attempt2", id)
}
-71
View File
@@ -7,7 +7,6 @@ import (
"context"
"encoding/json"
"image/jpeg"
"io"
"net/http"
"os"
"os/exec"
@@ -24,76 +23,6 @@ import (
"mtusi2026-messenger/internal/dto"
)
func workerCommand(t *testing.T, args ...string) string {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "docker", args...)
cmd.Dir = ".."
out, err := cmd.Output()
if err != nil {
t.Fatalf("Docker command failed: %v", err)
}
return strings.TrimSpace(string(out))
}
func workerSQL(t *testing.T, query string) string {
t.Helper()
return workerCommand(t, "compose", "exec", "-T", "postgres", "psql",
"-U", "messenger", "-d", "messenger", "-Atqc", query)
}
func workerWait(t *testing.T, description string, timeout time.Duration, condition func() bool) {
t.Helper()
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
if condition() {
return
}
time.Sleep(300 * time.Millisecond)
}
t.Fatalf("timeout waiting for %s", description)
}
func workerQueue(t *testing.T) string {
t.Helper()
out := workerCommand(t, "compose", "exec", "-T", "rabbitmq", "rabbitmqctl",
"list_queues", "name", "messages_ready", "messages_unacknowledged", "--silent")
for _, line := range strings.Split(out, "\n") {
fields := strings.Fields(line)
if len(fields) == 3 && fields[0] == "attachments.process.v1" {
return fields[1] + ":" + fields[2]
}
}
t.Fatal("attachment queue missing")
return ""
}
func workerUpload(t *testing.T, user testUser, chatID uuid.UUID) (dto.AttachmentResponse, []byte) {
t.Helper()
source := makePNG(t, 320, 200)
resp := uploadAttachment(t, user, chatID, "worker.png", "image/png", source)
requireStatus(t, resp, http.StatusAccepted)
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
if att.Status != "queued" {
t.Fatalf("expected queued, got %s", att.Status)
}
return att, source
}
func workerContent(t *testing.T, user testUser, id uuid.UUID, variant string) []byte {
t.Helper()
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+id.String()+"/content?variant="+variant, user.Token, nil)
requireStatus(t, resp, http.StatusOK)
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
return data
}
func TestWorkerPersistenceAndDuplicate(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
+2 -2
View File
@@ -17,7 +17,7 @@ help-go:
@echo "load-go: load test"
@echo "failure-go: dependency failure tests (stops redis/postgres/s3 containers)"
@echo "reconcile: attachment audit; DRY_RUN=false to repair"
@echo "pipeline-go: image pipeline versions (no running services required)"
@echo "pipeline-go: versioned pipeline tests (requires Compose; stops worker)"
contract-go:
go test -tags=contract ./student-tests/... -v -args -base-url=$(BASE_URL)
@@ -49,4 +49,4 @@ worker-go:
go test -count=1 -tags=worker ./student-tests/... -v -args -base-url=$(BASE_URL)
pipeline-go:
go test -count=1 -tags=nodynamic,pipeline ./student-tests/... -v
go test -count=1 -tags=nodynamic,pipeline ./student-tests/... -v -args -base-url=$(BASE_URL)