From ac30972d48c08370f1e0fb9c8326451e35758c9e Mon Sep 17 00:00:00 2001 From: Vladislav Kunetskiy Date: Sat, 31 Oct 2026 01:46:26 +0300 Subject: [PATCH] =?UTF-8?q?lab5:=20=D0=B7=D0=B0=D0=BA=D1=80=D1=8B=D1=82?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=BE=D1=81=D1=82=D0=B0=D1=82=D0=BE=D1=87=D0=BD?= =?UTF-8?q?=D1=8B=D1=85=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Validate tRNS semantics and bind PLTE entry count to the IHDR bit depth so malformed PNGs are rejected with 415 instead of failing in the worker. Refuse replay of an older failed version while a newer pipeline job exists, preventing loss of the shared staging source, and retire version-stale queued jobs as superseded instead of republishing them forever. --- REPORT.md | 4 +- evidence/lab5/async.txt | 2 +- evidence/lab5/attachments-negative.txt | 5 +- evidence/lab5/faults.txt | 4 +- evidence/lab5/integration-test.txt | 4 +- evidence/lab5/lint.txt | 18 ++-- evidence/lab5/smoke.txt | 2 +- evidence/lab5/unit-test.txt | 34 +++---- internal/imagecheck/imagecheck.go | 44 +++++++++ internal/imagecheck/imagecheck_test.go | 94 +++++++++++++++++++ .../storage/postgres/pipeline_repository.go | 35 +++++++ .../postgres/pipeline_repository_test.go | 84 +++++++++++++++++ student-tests/attachments_negative.py | 33 +++++++ student-tests/lab5_faults.py | 27 ++++++ 14 files changed, 357 insertions(+), 33 deletions(-) diff --git a/REPORT.md b/REPORT.md index b2dbf534..8cb935dc 100644 --- a/REPORT.md +++ b/REPORT.md @@ -110,7 +110,7 @@ flowchart LR | Полный restart стека | `lab5_async.py` | ready-вложение и original сохранились | `evidence/lab5/async.txt` | | Варианты: thumbnail/crop/optimized | `make test-queue`/`lab5_variants.py` | thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized WebP 320×200; metadata == bytes; EXIF отсутствует | `evidence/lab5/variants.txt` | | Состояния queued/processing/ready/failed | `lab5_async.py`, `lab5_faults.py` | queued/ready и failed/error_code наблюдаются через API | `evidence/lab5/async.txt`, `faults.txt` | -| 415 на невалидное изображение | `make test-attachments` | пустое тело, IDAT-CRC, MIME spoof, не-zlib IDAT, пустой растр, недопустимый scanline-фильтр, несовместимые color type/bit depth, дубликаты IHDR, мусор после zlib — 415 до 202 | `evidence/lab5/attachments-negative.txt` | +| 415 на невалидное изображение | `make test-attachments` | пустое тело, IDAT-CRC, MIME spoof, не-zlib IDAT, пустой растр, недопустимый scanline-фильтр, несовместимые color type/bit depth, дубликаты IHDR, мусор после zlib, битый tRNS, PLTE сверх bit depth — 415 до 202 | `evidence/lab5/attachments-negative.txt` | | Original неизменен | smoke + variants | скачанные байты и sha совпадают с загруженными | `evidence/lab5/smoke.txt`, `variants.txt` | | Retry/backoff/classification | `make test-faults` | permanent → failed сразу; transient → 5 attempts, 4 retry events, `retry_exhausted`; DLQ | `evidence/lab5/faults.txt` | | DLQ/registry + replay | `lab5_faults.py` | failed виден в `jobctl failed`; replay → ready; replay ready refused | `evidence/lab5/faults.txt` | @@ -152,6 +152,8 @@ flowchart LR | Reprocess queued при остановленном worker | v2 берёт проверенный staging, а не несуществующий original | pv=2 ready, v1 superseded, v2 ready | | Reprocess v2 падает до публикации | вложение терминально failed, не вечный queued | failed/error_code, active jobs 0 | | Replay упавшей v2 до публикации | API не показывает stale failed, работа возвращается | job queued, attachment queued, затем ready:v2 | +| Replay старой failed-v1 при наличии v2 | команда отклонена, источник v2 не потерян | v1 failed, v2 queued → ready:v2 | +| Version-stale queued job после публикации v2 | задание терминально superseded, не переиздаётся | claim → superseded, reconcile не создаёт работу | | Reprocess на неподдерживаемую версию | команда отклонена, v1-задание не тронуто | jobctl exit != 0, v1 queued → ready | Измерения: recovery времени и counts — из `evidence/lab5/faults.txt`, `track2/runs.csv`. diff --git a/evidence/lab5/async.txt b/evidence/lab5/async.txt index dbd89bda..a22d96fb 100644 --- a/evidence/lab5/async.txt +++ b/evidence/lab5/async.txt @@ -1,4 +1,4 @@ -# make test-queue 2026-10-30T22:19:06Z +# make test-queue 2026-10-30T22:43:35Z env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 student-tests/lab5_async.py --base-url "http://localhost:8080" worker down: 202 queued, content 409, queued attachment linked, API restarted worker restarted: ready, thumbnail and original downloadable, staging cleared diff --git a/evidence/lab5/attachments-negative.txt b/evidence/lab5/attachments-negative.txt index af69f36a..86e17e10 100644 --- a/evidence/lab5/attachments-negative.txt +++ b/evidence/lab5/attachments-negative.txt @@ -1,4 +1,4 @@ -# make test-attachments 2026-10-30T22:19:04Z +# make test-attachments 2026-10-30T22:43:33Z env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 student-tests/attachments_negative.py --base-url "http://localhost:8080" 10 MiB + 1 body: 413 empty body: 415 @@ -10,6 +10,9 @@ valid zlib, invalid PNG scanline filter: 415 invalid PNG color type/bit depth pair: 415 duplicate PNG IHDR: 415 trailing bytes after PNG zlib stream: 415 +tRNS on RGBA PNG: 415 +short tRNS on RGB PNG: 415 +PLTE entries exceed palette bit depth: 415 dangerous filenames: 400 foreign attachment metadata/content: 404 empty text without attachments: 400 diff --git a/evidence/lab5/faults.txt b/evidence/lab5/faults.txt index 39cd3792..779d7e55 100644 --- a/evidence/lab5/faults.txt +++ b/evidence/lab5/faults.txt @@ -1,8 +1,10 @@ -# make test-faults 2026-10-30T22:19:30Z +# make test-faults 2026-10-30T22:43:58Z env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 student-tests/lab5_faults.py --base-url "http://localhost:8080" permanent failure: failed/injected_failure, content 409, failed attachment not linkable, registry visible replay: failed -> queued -> ready, one thumbnail replay ready job: refused +replay older failed version while v2 queued: refused, state intact +v2 published after older replay refusal replay of failed reprocess: queued projection restored, then ready at pipeline 2 transient exhaustion: attempts=5, retry_exhausted, four retries, DLQ message present crash after first variant: redelivered, same three variants, attempts=2 diff --git a/evidence/lab5/integration-test.txt b/evidence/lab5/integration-test.txt index a612c13f..72365406 100644 --- a/evidence/lab5/integration-test.txt +++ b/evidence/lab5/integration-test.txt @@ -1,2 +1,2 @@ -ok mtusi-messenger/internal/storage/postgres 9.691s -ok mtusi-messenger/internal/storage/redis 1.246s +ok mtusi-messenger/internal/storage/postgres 9.740s +ok mtusi-messenger/internal/storage/redis 1.237s diff --git a/evidence/lab5/lint.txt b/evidence/lab5/lint.txt index 47b88386..8a0b0322 100644 --- a/evidence/lab5/lint.txt +++ b/evidence/lab5/lint.txt @@ -3,18 +3,18 @@ level=info msg="golangci-lint has version 2.13.2 built with go1.27.1 from (unkno level=info msg="[config_reader] Config search paths: [./ /Users/vladislav/Projects/mtusi2026lab5 /Users/vladislav/Projects /Users/vladislav /Users /]" level=info msg="[config_reader] Used config file .golangci.yml" level=info msg="[config_reader] Module name \"mtusi-messenger\"" -level=info msg="[goenv] Read go env for 6.440209ms: map[string]string{\"GOCACHE\":\"/Users/vladislav/Library/Caches/go-build\", \"GOROOT\":\"/opt/homebrew/Cellar/go/1.27.1/libexec\"}" +level=info msg="[goenv] Read go env for 7.230292ms: map[string]string{\"GOCACHE\":\"/Users/vladislav/Library/Caches/go-build\", \"GOROOT\":\"/opt/homebrew/Cellar/go/1.27.1/libexec\"}" level=info msg="[lintersdb] Active 50 linters: [asasalint bodyclose canonicalheader containedctx contextcheck copyloopvar depguard durationcheck errcheck errname errorlint exhaustive exptostd fatcontext forbidigo forcetypeassert gocheckcompilerdirectives gocritic gofumpt goimports gomoddirectives gosec govet ineffassign intrange makezero misspell musttag nilerr nilnil noctx nolintlint perfsprint prealloc reassign recvcheck revive rowserrcheck sloglint sqlclosecheck staticcheck testifylint thelper tparallel unconvert unparam unused usestdlibvars usetesting wastedassign]" level=info msg="[loader] Using build tags: [integration]" -level=info msg="[loader] Go packages loading at mode 8767 (compiled_files|deps|exports_file|imports|files|name|types_sizes) took 200.621833ms" -level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 10.581125ms" -level=info msg="[linters_context/goanalysis] analyzers took 0s with no stages" +level=info msg="[loader] Go packages loading at mode 8767 (deps|exports_file|files|imports|name|compiled_files|types_sizes) took 285.717958ms" +level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 10.492667ms" +level=info msg="[linters_context/goanalysis] analyzers took 21.264339055s with top 10 stages: goimports: 5.91549475s, revive: 3.740582125s, gosec: 1.775157082s, unparam: 1.224420001s, wastedassign: 868.611793ms, buildir: 477.238122ms, buildssa: 376.629332ms, nilness: 292.332672ms, sloglint: 234.71729ms, gofumpt: 218.928999ms" level=info msg="[runner/exclusion_rules] Skipped 14 issues by rules: [Path: \"_test\\\\.go\", Linters: \"gosec, prealloc, forcetypeassert, unparam\"]" level=info msg="[runner] Issues before processing: 887, after processing: 0" -level=info msg="[runner] Processors filtering stat (in/out): exclusion_paths: 887/887, path_absoluter: 887/887, cgo: 887/887, invalid_issue: 887/887, exclusion_rules: 298/6, filename_unadjuster: 887/887, path_relativity: 887/887, nolint_filter: 6/0, generated_file_filter: 887/298" -level=info msg="[runner] processing took 3.023042ms with stages: generated_file_filter: 1.594792ms, nolint_filter: 794.292µs, path_relativity: 317.917µs, exclusion_rules: 278.458µs, invalid_issue: 13.25µs, cgo: 12.166µs, path_absoluter: 6.167µs, filename_unadjuster: 2.875µs, sort_results: 875ns, max_same_issues: 625ns, exclusion_paths: 416ns, fixer: 250ns, path_prettifier: 209ns, diff: 167ns, source_code: 167ns, max_per_file_from_linter: 125ns, path_shortener: 125ns, max_from_linter: 83ns, uniq_by_line: 83ns, severity-rules: 0s" -level=info msg="[runner] linters took 663.901083ms with stages: goanalysis_metalinter: 660.828ms" +level=info msg="[runner] Processors filtering stat (in/out): path_absoluter: 887/887, cgo: 887/887, filename_unadjuster: 887/887, generated_file_filter: 887/298, exclusion_paths: 887/887, invalid_issue: 887/887, path_relativity: 887/887, exclusion_rules: 298/6, nolint_filter: 6/0" +level=info msg="[runner] processing took 2.876665ms with stages: generated_file_filter: 1.76725ms, nolint_filter: 552.542µs, path_relativity: 268.125µs, exclusion_rules: 249.625µs, invalid_issue: 13.541µs, cgo: 12.251µs, path_absoluter: 6.125µs, sort_results: 2.875µs, filename_unadjuster: 2.792µs, max_same_issues: 333ns, fixer: 291ns, path_shortener: 249ns, max_per_file_from_linter: 209ns, exclusion_paths: 208ns, path_prettifier: 166ns, diff: 42ns, uniq_by_line: 41ns, max_from_linter: 0s, source_code: 0s, severity-rules: 0s" +level=info msg="[runner] linters took 2.891797125s with stages: goanalysis_metalinter: 2.888879125s" 0 issues. level=info msg="File cache stats: 0 entries of total size 0B" -level=info msg="Memory: 10 samples, avg is 91.9MB, max is 127.5MB" -level=info msg="Execution took 882.402625ms" +level=info msg="Memory: 33 samples, avg is 393.4MB, max is 704.0MB" +level=info msg="Execution took 3.196263875s" diff --git a/evidence/lab5/smoke.txt b/evidence/lab5/smoke.txt index 6aea81e8..dcd54629 100644 --- a/evidence/lab5/smoke.txt +++ b/evidence/lab5/smoke.txt @@ -1,3 +1,3 @@ -# make test 2026-10-30T22:19:26Z +# make test 2026-10-30T22:43:54Z env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 tests/smoke.py --base-url "http://localhost:8080" PASS: lab5 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/lab5/unit-test.txt b/evidence/lab5/unit-test.txt index d55d3234..d1fa8c71 100644 --- a/evidence/lab5/unit-test.txt +++ b/evidence/lab5/unit-test.txt @@ -6,35 +6,35 @@ env -u APP_ENV -u SERVER_HOST -u SERVER_PORT -u SERVER_READ_HEADER_TIMEOUT -u SE ? mtusi-messenger/cmd/s3init [no test files] ? mtusi-messenger/cmd/worker [no test files] ? mtusi-messenger/internal/broker [no test files] -ok mtusi-messenger/internal/config 1.556s -ok mtusi-messenger/internal/domain 2.720s +ok mtusi-messenger/internal/config 2.864s +ok mtusi-messenger/internal/domain 2.165s ? mtusi-messenger/internal/failpoint [no test files] -ok mtusi-messenger/internal/health 1.789s -ok mtusi-messenger/internal/imagecheck 2.116s -ok mtusi-messenger/internal/imageproc 3.443s -ok mtusi-messenger/internal/logger 2.441s +ok mtusi-messenger/internal/health 3.964s +ok mtusi-messenger/internal/imagecheck 1.632s +ok mtusi-messenger/internal/imageproc 1.734s +ok mtusi-messenger/internal/logger 3.393s ? mtusi-messenger/internal/outbox [no test files] -ok mtusi-messenger/internal/platform/cache 3.537s +ok mtusi-messenger/internal/platform/cache 2.618s ? mtusi-messenger/internal/platform/cache/mocks [no test files] -ok mtusi-messenger/internal/platform/objectstore 3.995s -ok mtusi-messenger/internal/platform/password 4.080s -ok mtusi-messenger/internal/platform/token 3.091s -ok mtusi-messenger/internal/service/attachment 4.331s +ok mtusi-messenger/internal/platform/objectstore 3.077s +ok mtusi-messenger/internal/platform/password 2.238s +ok mtusi-messenger/internal/platform/token 4.261s +ok mtusi-messenger/internal/service/attachment 5.207s ? mtusi-messenger/internal/service/attachment/mocks [no test files] -ok mtusi-messenger/internal/service/chat 4.626s +ok mtusi-messenger/internal/service/chat 4.889s ? mtusi-messenger/internal/service/chat/mocks [no test files] -ok mtusi-messenger/internal/service/message 4.943s +ok mtusi-messenger/internal/service/message 5.511s ? mtusi-messenger/internal/service/message/mocks [no test files] -ok mtusi-messenger/internal/service/session 5.870s +ok mtusi-messenger/internal/service/session 4.899s ? mtusi-messenger/internal/service/session/mocks [no test files] -ok mtusi-messenger/internal/service/user 6.026s +ok mtusi-messenger/internal/service/user 3.864s ? mtusi-messenger/internal/service/user/mocks [no test files] -ok mtusi-messenger/internal/storage/postgres 5.253s +ok mtusi-messenger/internal/storage/postgres 5.476s ? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files] ? mtusi-messenger/internal/storage/postgres/migrations [no test files] ? mtusi-messenger/internal/storage/redis [no test files] ? mtusi-messenger/internal/storage/redis/mocks [no test files] -ok mtusi-messenger/internal/transport/rest 6.240s +ok mtusi-messenger/internal/transport/rest 5.863s ? mtusi-messenger/internal/transport/rest/internal/oas [no test files] ? mtusi-messenger/internal/transport/rest/mocks [no test files] ? mtusi-messenger/internal/worker [no test files] diff --git a/internal/imagecheck/imagecheck.go b/internal/imagecheck/imagecheck.go index f3676f30..6da63984 100644 --- a/internal/imagecheck/imagecheck.go +++ b/internal/imagecheck/imagecheck.go @@ -82,7 +82,9 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) { first = true hasIDAT bool paletteReady bool + trnsSeen bool colorType byte + bitDepth byte idat bytes.Buffer raster []pngPass rasterBytes int64 @@ -166,6 +168,7 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) { info.Width = int64(binary.BigEndian.Uint32(data[0:4])) info.Height = int64(binary.BigEndian.Uint32(data[4:8])) colorType = data[9] + bitDepth = data[8] if info.Width <= 0 || info.Height <= 0 { return Info{}, corruptf("png dimensions %dx%d", info.Width, info.Height) @@ -201,9 +204,50 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) { return Info{}, corruptf("png PLTE length %d", length) } + if length/3 > 1< 256 { + return Info{}, corruptf("png tRNS length %d", length) + } + default: + return Info{}, corruptf("png tRNS invalid for color type %d", colorType) + } + + trnsSeen = true case "IEND": if length != 0 { return Info{}, corruptf("png IEND length %d", length) diff --git a/internal/imagecheck/imagecheck_test.go b/internal/imagecheck/imagecheck_test.go index e7e42d33..81b9494f 100644 --- a/internal/imagecheck/imagecheck_test.go +++ b/internal/imagecheck/imagecheck_test.go @@ -318,6 +318,100 @@ func TestValidateAcceptsStandardEncodings(t *testing.T) { } } +func TestValidateRejectsPNGPLTEEntriesExceedBitDepth(t *testing.T) { + data := pngFile( + pngChunk("IHDR", pngIHDR(1, 1, 1, 3, 0)), + pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0, 0, 0, 255}), + pngChunk("IDAT", zlibBytes(t, []byte{0, 0})), + pngChunk("IEND", nil), + ) + + _, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000) + require.ErrorIs(t, err, imagecheck.ErrCorrupt) +} + +func TestValidateRejectsInvalidTRNS(t *testing.T) { + rgb := pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30})) + gray := pngChunk("IDAT", zlibBytes(t, []byte{0, 10})) + rgba := pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30, 255})) + paletted := pngChunk("IDAT", zlibBytes(t, []byte{0, 0})) + + cases := map[string][]byte{ + "tRNS on RGBA": pngFile( + pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0)), + pngChunk("tRNS", []byte{0}), + rgba, + pngChunk("IEND", nil), + ), + "RGB length": pngFile( + pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)), + pngChunk("tRNS", []byte{0}), + rgb, + pngChunk("IEND", nil), + ), + "gray length": pngFile( + pngChunk("IHDR", pngIHDR(1, 1, 8, 0, 0)), + pngChunk("tRNS", []byte{0}), + gray, + pngChunk("IEND", nil), + ), + "palette before PLTE": pngFile( + pngChunk("IHDR", pngIHDR(1, 1, 8, 3, 0)), + pngChunk("tRNS", []byte{0}), + pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0}), + paletted, + pngChunk("IEND", nil), + ), + "duplicate tRNS": pngFile( + pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)), + pngChunk("tRNS", make([]byte, 6)), + pngChunk("tRNS", make([]byte, 6)), + rgb, + pngChunk("IEND", nil), + ), + "tRNS after IDAT": pngFile( + pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)), + rgb, + pngChunk("tRNS", make([]byte, 6)), + pngChunk("IEND", nil), + ), + } + + for name, data := range cases { + _, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000) + require.ErrorIs(t, err, imagecheck.ErrCorrupt, name) + } +} + +func TestValidateAcceptsValidTRNS(t *testing.T) { + cases := map[string][]byte{ + "RGB": pngFile( + pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)), + pngChunk("tRNS", make([]byte, 6)), + pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30})), + pngChunk("IEND", nil), + ), + "gray": pngFile( + pngChunk("IHDR", pngIHDR(1, 1, 8, 0, 0)), + pngChunk("tRNS", make([]byte, 2)), + pngChunk("IDAT", zlibBytes(t, []byte{0, 10})), + pngChunk("IEND", nil), + ), + "palette": pngFile( + pngChunk("IHDR", pngIHDR(1, 1, 1, 3, 0)), + pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0}), + pngChunk("tRNS", []byte{128}), + pngChunk("IDAT", zlibBytes(t, []byte{0, 0})), + pngChunk("IEND", nil), + ), + } + + for name, data := range cases { + _, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000) + require.NoError(t, err, name) + } +} + // A valid Adam7 stream for a tall, narrow image exceeds the old // (rowBytes+1)*(height+8) guess; the exact pass layout must accept it. func TestValidateAcceptsAdam7PNG(t *testing.T) { diff --git a/internal/storage/postgres/pipeline_repository.go b/internal/storage/postgres/pipeline_repository.go index 6182da0e..ca4d3e4d 100644 --- a/internal/storage/postgres/pipeline_repository.go +++ b/internal/storage/postgres/pipeline_repository.go @@ -578,6 +578,23 @@ func (r *PipelineRepository) ClaimJob( switch { case job.PipelineVersion < attachment.PipelineVersion: + // A queued job left behind by an older version (for example a + // replay accepted before the newer version committed) can never + // make progress. Retire it instead of acknowledging and + // republishing it through reconciliation forever. + if job.Status == domain.JobQueued { + if _, err := tx.Exec(ctx, ` + UPDATE attachment_jobs + SET status = 'superseded', updated_at = now(), completed_at = now() + WHERE job_id = $1 AND status = 'queued'`, job.ID); err != nil { + return fmt.Errorf("supersede version-stale job: %w", mapError(err)) + } + + if err := insertEventTx(ctx, tx, job.ID, domain.EventSuperseded, job.Attempt, ""); err != nil { + return err + } + } + result.Outcome = domain.ClaimVersionStale return nil @@ -1455,6 +1472,24 @@ func (r *PipelineRepository) ReplayJob( return fmt.Errorf("%w: job is superseded by a newer pipeline version", domain.ErrConflict) } + // A newer version may still be unpublished (attachment.pipeline_version + // changes only when it commits), so compare against job rows too. An + // older replay must not compete with a newer job for the same staging + // source or return the attachment to an older state. + var newerJob bool + + if err := tx.QueryRow(ctx, ` + SELECT EXISTS ( + SELECT 1 FROM attachment_jobs + WHERE attachment_id = $1 AND pipeline_version > $2 + )`, job.AttachmentID, job.PipelineVersion).Scan(&newerJob); err != nil { + return fmt.Errorf("check newer pipeline version: %w", mapError(err)) + } + + if newerJob { + return fmt.Errorf("%w: a newer pipeline version already has a job", domain.ErrConflict) + } + nextAttempt := job.Attempt + 1 _, err = tx.Exec(ctx, ` diff --git a/internal/storage/postgres/pipeline_repository_test.go b/internal/storage/postgres/pipeline_repository_test.go index 435c8e32..40c725d7 100644 --- a/internal/storage/postgres/pipeline_repository_test.go +++ b/internal/storage/postgres/pipeline_repository_test.go @@ -413,6 +413,90 @@ func (s *PipelineSuite) TestReplayNewerFailedVersionKeepsReadyServingVersion() { s.Nil(current.ErrorCode) } +// Replaying an older failed version is refused while a newer job exists, +// even before that newer version becomes the published serving version. +func (s *PipelineSuite) TestReplayOlderFailedVersionRefusedWhenNewerJobExists() { + alice := s.createUser("alice") + chat := s.createChat(alice) + repo := s.store.Pipeline() + + draft, job := s.attachmentDraft(chat, alice, 1) + _, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{}) + s.Require().NoError(err) + + claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-1", time.Minute) + s.Require().NoError(err) + s.Equal(domain.ClaimAcquired, claim.Outcome) + + failed, err := repo.FailJob(s.T().Context(), job.ID, 1, "lease-1", "invalid_image") + s.Require().NoError(err) + s.True(failed) + + reprocessID, err := uuid.NewV7() + s.Require().NoError(err) + + _, err = repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID) + s.Require().NoError(err) + + _, err = repo.ReplayJob(s.T().Context(), job.ID, 1) + s.Require().ErrorIs(err, domain.ErrConflict) + + var v1Status string + s.Require().NoError(s.pool.QueryRow(s.T().Context(), + `SELECT status FROM attachment_jobs WHERE job_id = $1`, job.ID).Scan(&v1Status)) + s.Equal(string(domain.JobFailed), v1Status) +} + +// A queued job for an older version is retired on claim instead of being +// acknowledged and republished by reconciliation forever. +func (s *PipelineSuite) TestClaimRetiresVersionStaleQueuedJob() { + alice := s.createUser("alice") + chat := s.createChat(alice) + repo := s.store.Pipeline() + + draft, job := s.attachmentDraft(chat, alice, 1) + _, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{}) + s.Require().NoError(err) + + reprocessID, err := uuid.NewV7() + s.Require().NoError(err) + + reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID) + s.Require().NoError(err) + + claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute) + s.Require().NoError(err) + s.Equal(domain.ClaimAcquired, claim.Outcome) + + variants := []domain.Variant{ + { + Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11, + Width: 256, Height: 160, SHA256: strings.Repeat("d", 64), + ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 2, domain.VariantThumbnail), + }, + } + + ok, err := repo.CompleteJob(s.T().Context(), reprocess.ID, 1, "lease-2", variants) + s.Require().NoError(err) + s.True(ok) + + // Simulate a legacy/racing replay that left the old version queued. + _, err = s.pool.Exec(s.T().Context(), ` + UPDATE attachment_jobs + SET status = 'queued', attempt = 1, last_error_code = NULL + WHERE job_id = $1`, job.ID) + s.Require().NoError(err) + + stale, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-3", time.Minute) + s.Require().NoError(err) + s.Equal(domain.ClaimVersionStale, stale.Outcome) + + var status string + s.Require().NoError(s.pool.QueryRow(s.T().Context(), + `SELECT status FROM attachment_jobs WHERE job_id = $1`, job.ID).Scan(&status)) + s.Equal(string(domain.JobSuperseded), status) +} + func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() { alice := s.createUser("alice") chat := s.createChat(alice) diff --git a/student-tests/attachments_negative.py b/student-tests/attachments_negative.py index 989a81cf..1b40378f 100755 --- a/student-tests/attachments_negative.py +++ b/student-tests/attachments_negative.py @@ -33,10 +33,19 @@ def png_chunk(ctype, payload): def crafted_png(width, height, interlace, raster, bit_depth=8, color_type=6): """PNG with correct chunk lengths and CRCs around arbitrary IDAT bytes.""" + return crafted_png_extra( + width, height, raster, bit_depth=bit_depth, color_type=color_type, + interlace=interlace, + ) + + +def crafted_png_extra(width, height, raster, pre_idat=(), bit_depth=8, color_type=6, interlace=0): + """PNG whose IDAT is preceded by caller-supplied chunks (PLTE/tRNS/...).""" ihdr = struct.pack('>IIBBBBB', width, height, bit_depth, color_type, 0, 0, interlace) return ( b'\x89PNG\r\n\x1a\n' + png_chunk(b'IHDR', ihdr) + + b''.join(pre_idat) + png_chunk(b'IDAT', zlib.compress(raster)) + png_chunk(b'IEND', b'') ) @@ -112,6 +121,30 @@ def main(): upload(client, alice, chat, trailing, expected=415) print('trailing bytes after PNG zlib stream: 415') + # tRNS is forbidden for alpha color types and has fixed lengths otherwise. + rgba_trns = crafted_png_extra( + 1, 1, b'\x00' + b'\x00' * 4, + pre_idat=(png_chunk(b'tRNS', b'\x00'),), color_type=6, + ) + upload(client, alice, chat, rgba_trns, expected=415) + print('tRNS on RGBA PNG: 415') + + rgb_trns = crafted_png_extra( + 1, 1, b'\x00' + b'\x00' * 3, + pre_idat=(png_chunk(b'tRNS', b'\x00'),), color_type=2, + ) + upload(client, alice, chat, rgb_trns, expected=415) + print('short tRNS on RGB PNG: 415') + + # A 1-bit palette cannot address three entries. + palette_overflow = crafted_png_extra( + 1, 1, b'\x00\x00', + pre_idat=(png_chunk(b'PLTE', bytes((255, 0, 0, 0, 255, 0, 0, 0, 255))),), + bit_depth=1, color_type=3, + ) + upload(client, alice, chat, palette_overflow, expected=415) + print('PLTE entries exceed palette bit depth: 415') + # Dangerous display names. for name in ('../x.png', 'a/b.png', 'a\\b.png', 'a\x00.png', 'a\n.png'): upload(client, alice, chat, fixture, filename=name, expected=400) diff --git a/student-tests/lab5_faults.py b/student-tests/lab5_faults.py index 8e246499..0df32834 100755 --- a/student-tests/lab5_faults.py +++ b/student-tests/lab5_faults.py @@ -268,6 +268,32 @@ def scenario_replay_reprocessed_version(client, alice, chat): print('replay of failed reprocess: queued projection restored, then ready at pipeline 2') +def scenario_replay_older_version_refused(client, alice, chat): + compose('stop', 'worker') + attached, _ = client.attachment(alice, chat) + jid_v1 = job_id(attached['id']) + + worker_with(FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid_v1, FAULT_WORKER_FAIL='permanent') + status, code, _ = wait_db(attached['id'], lambda s, e, a: s == 'failed', 40, 'failed v1') + check(code == 'injected_failure', 'unexpected v1 failure: ' + code) + + compose('stop', 'worker') + reprocessed = json.loads(jobctl('reprocess', '-attachment', attached['id'], '-pipeline', '2').stdout) + refused = jobctl('replay', '-job', jid_v1, check=False) + check(refused.returncode != 0, 'older failed version was replayed while v2 exists') + jobs = psql("select pipeline_version || ':' || status from attachment_jobs where attachment_id='%s' order by pipeline_version" % attached['id']) + check(jobs == '1:failed\n2:queued', 'older replay changed job state: ' + jobs.replace('\n', ', ')) + print('replay older failed version while v2 queued: refused, state intact') + + reset_worker() + client.wait_ready(alice, attached, wait_seconds=90) + check(psql("select pipeline_version from attachments where id='%s'" % attached['id']) == '2', + 'v2 did not publish after older replay was refused') + check(psql("select job_id from attachment_jobs where attachment_id='%s' and pipeline_version=2" % attached['id']) == reprocessed['ID'], + 'v2 job identity changed') + print('v2 published after older replay refusal') + + def main(): args = arguments('Lab5 level 4 fault injection') client = Client(args.base_url, args.ca_file) @@ -275,6 +301,7 @@ def main(): scenarios = [ scenario_permanent_failure_and_replay, + scenario_replay_older_version_refused, scenario_replay_reprocessed_version, scenario_transient_exhaustion, scenario_crash_after_first_variant,