81 Commits
Author SHA1 Message Date
Artyom c67dd11029 Merge completed lab 4 for Gitea submission
Preserve the exact lab 4 tree and original history from 4ed889c1e4.
Connect it to the instructor master for a cross-fork pull request.
2026-11-08 00:57:05 +03:00
Artyom 4ed889c1e4 Validate final PNG workloads and retain applicable evidence 2026-11-06 22:21:55 +03:00
Artyom 5e49502ae7 Finalize lab4 report and evidence provenance after review 2026-11-06 21:53:18 +03:00
Artyom 7a0ebac2aa Archive the PNG header consistency change 2026-11-06 21:34:36 +03:00
Artyom 7c8a1a6489 Reject ambiguous PNG headers before pixel validation 2026-11-06 21:33:09 +03:00
Artyom bcbd4ebc02 Propose PNG header consistency as an OpenSpec change 2026-11-06 21:29:25 +03:00
Artyom 7342d5d97a Archive the PNG validation fix and record offline evidence 2026-11-06 13:00:51 +03:00
Artyom 9387c3d82a Reject corrupt PNG pixels with bounded stream validation 2026-11-06 12:57:32 +03:00
Artyom f0521fa1e0 Propose bounded PNG validation as an openspec change 2026-11-06 12:49:16 +03:00
Artyom 8bc2da2c09 Verify and archive final lab3 fixes for lab4 2026-11-06 12:33:49 +03:00
Artyom 75b93bbba5 Forward final lab3 session security and validation fixes 2026-11-06 12:07:00 +03:00
Artyom f0fc084fbb Propose forwarding final lab3 review fixes 2026-11-06 12:01:57 +03:00
Artyom d7478726a8 Complete SQLAlchemy reconciler evidence and close lab4 review findings 2026-11-06 03:37:31 +03:00
Artyom 504f77cb7c Validate reconciler evidence and expose isolated demo output 2026-11-06 03:32:06 +03:00
Artyom 3402fd69d4 Expose bounded seed progress for long reconciler experiments 2026-11-06 02:32:19 +03:00
Artyom 827b783be3 Reject disturbed reconciler measurements and preserve every series 2026-11-06 02:29:53 +03:00
Artyom 751aaed4b1 Preregister SQLAlchemy reconciler validation and full cost matrix 2026-11-06 02:28:14 +03:00
Artyom 57caeb6b5a Verify grade four faults memory cleanup and clean clone on SQLAlchemy 2026-11-06 02:27:08 +03:00
Artyom cf41f7c64d Separate historical results and audit every lab4 review finding 2026-11-06 02:07:59 +03:00
Artyom 6c706a727e Preserve evidence runs and volumes while propagating failures 2026-11-06 02:02:04 +03:00
Artyom c7e7a86627 Propose isolated grade four verification and review closure 2026-11-06 02:01:27 +03:00
Artyom 02f385866f Verify and archive lab4 grade three on SQLAlchemy 2026-11-06 02:00:43 +03:00
Artyom 763b025557 Fail attachment scenarios on invalid outcomes 2026-11-06 01:59:03 +03:00
Artyom 1aec062aba Capture isolated evidence with full provenance and exit codes 2026-11-06 01:54:30 +03:00
Artyom 5596ca935c Propose fresh lab4 grade three evidence on SQLAlchemy 2026-11-06 01:54:07 +03:00
Artyom 41700c27e5 Archive the lab3 foundation forward port 2026-11-06 01:48:09 +03:00
Artyom 8e4532f6f5 Forward-port lab3 SQLAlchemy and Alembic foundation
Carry source f591fa64e5 forward from 72a1e57. Preserve lab4 attachment transactions, reconciliation locks, quarantine, and existing schema data through verified legacy adoption. Keep report and evidence work in progress untouched.
2026-11-06 01:47:30 +03:00
Artyom dd4021b678 Propose the lab3 SQLAlchemy foundation forward port 2026-11-06 01:32:54 +03:00
ArtyomandClaude Opus 5.5 568ff6643e Archive the storage reconciler hardening change
A pass releases the quarantine only after the object hashes to the row
again, reads exactly ceil(N/page) SQL pages, publishes
audit.attachment_discarded reason=reconcile for the intents it drops,
is assembled by dishka with the same storage provider as the API and
ends any failure as reconcile.failed with exit code 1. The demo passes
13 of 13 checks, and the cost matrix up to 100k confirms the request
counts and the constant memory of H2 and refutes its linear time at
100k (19.6 instead of 10 +- 30 %, the RustFS listing page grows from
91 to 197 ms). student-test (348), test, persistence and failover pass
on the stand. The requirements are synced into lab4-storage-reconciler.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 09:54:40 +03:00
ArtyomandClaude Opus 5.5 d2e684f0cf Record the track 2 demo and the cost of a pass up to 100k
The demo on a clean stand (61dcb6b) passes 13 of 13 checks: the dry-run
finds exactly the injected ids in every class, apply writes one
audit.attachment_discarded reason=reconcile per stale intent, the
original bytes leave the quarantine while random bytes of the same
length keep it, docker stop ends a pass hanging on a paused S3 in
0.11 s with exit code 143, and 74 passes during 3454 uploads lose no
ready attachment; 46 times the HEAD recheck kept an in-flight upload
out of the quarantine.

The cost matrix now reaches 100k: a shallow pass takes 0.108 / 1.032 /
3.761 / 20.211 s for 1k / 10k / 30k / 100k with ceil(N/1000) listings
and SQL pages and the same 87-88 MiB of RSS. t(100k)/t(10k) is 19.6,
outside the preregistered 10 +- 30 %, because a RustFS listing page
costs 91 ms at 1k and 197 ms at 100k objects in the prefix; the
reconciler's own CPU and SQL stay linear. The previous 30k series moves
to cost-b191623/, and the old after-checks give way to the full series
that follows the track.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 09:54:29 +03:00
ArtyomandClaude Opus 5.5 6ffb90d1d1 Script the overload leftovers check with raw output
overload-leftovers.txt was assembled by hand with summarised reconciler
reports. make overload-leftovers now runs the dry-run, the status
counts, the wait for the sweep after the grace period, the audit and
swept counts of the replicas and the dry-run afterwards, and writes
their raw output.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 09:17:15 +03:00
ArtyomandClaude Opus 5.5 61dcb6bf13 Keep the audit journal of each reconciler pass in its report
The driver now stores the audit events a pass writes to stderr next to
its JSON report, and the apply check requires one
audit.attachment_discarded reason=reconcile for every injected stale
intent.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 09:09:15 +03:00
ArtyomandClaude Opus 5.5 21937f920f Wait for S3 to turn healthy after the paused pass
docker compose up --wait failed at once after unpausing S3: the probes
that ran while it was paused had already marked it unhealthy. The demo
now polls the health status of the container until it is healthy again.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 09:04:09 +03:00
ArtyomandClaude Opus 5.5 f1ee385a1b Tie the track tooling to keys, sets and a clean series
reconcile-inject.sh wrote an orphan under a key whose uuid differed
from the id it printed, so the demo could only compare counts; it now
uses one uuid for both, and the dry-run check compares the found and
the injected sets per class. The heal step returns the original bytes
under one quarantined key and random bytes of the same length under
another, and checks that only the first leaves the quarantine. The
load phase sums rechecked over its passes, and a new step stops a pass
hanging on a paused S3 with docker stop and checks exit code 143 within
seconds and a free lock afterwards.

reconcile_track.py cost clears the run files of the previous series and
measures 1k, 10k, 30k and 100k with --deep everywhere. The scenarios
record date, commit and docker inspect of the replicas or of S3 at the
moment they are down. make load-evidence and make clean-clone-evidence
rerun the message load and the clean clone block with raw output, and
make upload-memory passes ARGS to reproduce the run directories.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 09:01:39 +03:00
ArtyomandClaude Opus 5.5 3de1dcdc84 Release the quarantine only after the object hashes to the row again
A pass without --deep released the quarantine of a missing or resized
attachment as soon as an object of the same size appeared under its
key, so other bytes of the same length went back to /content. The pass
now streams and hashes the object of every quarantined row whose size
matches again, deep or not, and releases it only when the SHA-256
matches; other bytes keep the row quarantined. Consistent data still
costs no GET.

The keyset reads page + 1 rows, so a pass takes exactly ceil(N/page)
SQL pages instead of one more for the empty tail. The reconciler is
assembled by dishka from PlatformProvider and the attachment storage
provider that the API uses too, and it publishes the events of the
intents it drops, so audit.attachment_discarded reason=reconcile
reaches the journal. Any failure of a pass, not only Unavailable, ends
as reconcile.failed with the error type and exit code 1.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 09:01:39 +03:00
ArtyomandClaude Opus 5.5 b6c04f2296 Propose hardening the storage reconciler as an openspec change
The review of track 2 found that a pass without --deep released the
quarantine of a missing or resized attachment as soon as an object of
the same size reappeared, without checking its SHA-256; that the keyset
read an empty last page, one SQL request more than the spec promised;
that the discarded intents of a pass never reached the audit journal;
that the entry point duplicated the S3 client wiring and printed a
traceback for any failure other than Unavailable; and that the cost
matrix stopped at 30k while the preregistered H2 was about 100k.

The change hashes the object of a quarantined row before releasing it,
reads page + 1 rows, assembles the reconciler with dishka and publishes
its events, turns any pass failure into reconcile.failed, links the
injected orphans to the found ones by key and measures up to 100k.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 08:56:15 +03:00
ArtyomandClaude Opus 5.5 adca7c6edc Archive the attachment boundaries change
Upload checks the token before the declared size, a slow but steady
transfer outlives the request timeout while a stalled one is still cut,
the API and the reconciler hold separate minimal S3 keys, and the
one-off services run as non-root with an init process. On the stand a
3 MiB upload at 256 KiB/s took 12.1 s at the replica and got 201, a
3 MiB download at 192 KiB/s took 12.8 s and matched the SHA-256, the
API key is denied a bucket listing, and docker stop ends a hanging
reconciler pass in 0.13 s with exit code 143. student-test (345),
test-faults (19), persistence, failover and the lab 4 scenarios pass.
The requirements are synced into lab4-attachments, lab4-upload-resilience
and lab4-object-storage.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 08:53:53 +03:00
ArtyomandClaude Opus 5.5 2891b37e75 Split the S3 keys of the API and the reconciler, drop root from one-offs
The API key now has only GetObject, PutObject and DeleteObject on the
attachment objects: the server never lists the bucket, never runs
multipart uploads and has its region set. The reconciler gets its own
user messenger-reconciler with ListBucket, GetObject and DeleteObject,
created by s3-init from a secret of its own, so the API replicas can no
longer list the bucket. The cost seeding writes objects and therefore
runs in a one-off API container under the API key. s3-check proves the
API key cannot list and checks the reconciler key; its snapshot drops
dated fields with a JSON filter instead of grep, which left a dangling
comma, and its first line carries the date and the commit.

s3-init and s3-cli run as uid 65534, and migrate and reconciler get an
init process, so SIGTERM reaches python and docker stop ends a pass in
a fraction of a second instead of waiting for SIGKILL. limits.py and CI
check the users of the one-off services. Stack tests move a 3 MiB file
up and down through the balancer at 256 and 192 KiB/s, longer than the
request timeout, and check 401 before the declared size.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 08:53:39 +03:00
ArtyomandClaude Opus 5.5 54099e1da3 Check the token before the declared size and pace the request deadline
The pipeline now runs the guard first, so an anonymous upload with a too
large Content-Length gets 401 with WWW-Authenticate, as the contract
asks; the guard does not read the body, so 413 still comes before the
first body byte for an authenticated client.

The single request deadline cut slow but steady uploads and downloads:
a client slower than about 1.3 MB/s could not move 10 MiB in 8 s. Each
body chunk the application receives or sends now moves the deadline to
min(now, start + moved / MIN_TRANSFER_RATE_BYTES) + REQUEST_TIMEOUT,
128 KiB/s by default, like mod_reqtimeout with a ceiling: a steady
transfer lives as long as it moves, a stalled or crawling body is cut
after the request timeout as before, and the work after the last body
byte still gets at most the request timeout. The pipeline's own error
responses bypass the pacing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 08:53:39 +03:00
ArtyomandClaude Opus 5.5 96e934ed8f Propose tightening the lab 4 attachment boundaries as an openspec change
The review of lab 4 found four gaps at the attachment boundaries: an
anonymous upload with a too large Content-Length got 413 before 401,
the single request deadline cut slow but steady uploads and downloads,
the API S3 key could list the bucket and run multipart actions, and the
one-off services ran as root or as PID 1 without an init process.

The change checks the token first, paces the request deadline by the
bytes moved, splits the S3 keys of the API and of the reconciler and
runs the one-off services as non-root with an init process.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 08:41:27 +03:00
ArtyomandClaude Opus 5.5 c8cb263c77 Retake the lab 4 evidence on the final code and finish the report
The level 3 and 4 evidence was taken on 24f9d61 and a774a2f, before the
lab 3 fixes were carried over and before the reconciler. Take all of it
again in one series on 81dd816, whose application and stand code is the
final one: a fresh clone runs the launch block of the report from secrets
to reset-data, then one stand from clean volumes gives the smoke, stack,
limits, lb-check, failover of each replica and of the upload replica,
persistence, S3 outage, S3 privacy, lost-answer retry, upload faults, all
stack checks, storage layout and three runs of the upload memory matrix.

The three memory runs keep the peak with three slots at 297-345 MiB
against 512 MiB at the limit without them, but at 40 uploads of 10 MiB
the wait for a slot nears the 8 s request timeout and one run of three
gave 7 of 80 a 503. Those timeouts left 67 invisible intents; the record
shows the reconciler seeing them as fresh and the sweep removing all of
them after the grace period.

Message write load is taken with tests/load.py from a container on the
edge network: 2 106 RPS, no errors, replicas and PostgreSQL at their CPU
limits. The first try from the macOS host is kept as a discarded attempt,
it ran out of ephemeral ports while the replicas answered every request.

The report gets the defense answers, the load section, the evidence
commits, the upload limit order as the pipeline applies it, medians in
the track 2 cost table and the proposals over the word limit; the evidence
index lists every file with its command and commit.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 07:55:34 +03:00
ArtyomandClaude Opus 5.5 81dd816df2 Archive the storage reconciler change
Track 2 of lab 4 is closed. One reconciler pass merges the sorted bucket
listing with keyset pages of attachments by object key, finds objects
without a row, ready rows without an object or with other bytes and
abandoned intents, deletes only old objects without a row after a
second look at the row and old intents under SKIP LOCKED, and puts
damaged ready rows into a reversible quarantine instead of deleting
them. On the stand the dry-run found exactly the 22 injected
discrepancies of seven classes, apply fixed the 18 fixable ones, the
repeat did nothing, and 75 passes during 3418 uploads lost no ready
attachment. A shallow pass costs 0.105 / 1.000 / 3.729 s for 1k / 10k /
30k objects at a flat 83 MiB, 95 % of it in the RustFS listing; --deep
is 4.3-5 times dearer per object.

For the defence: make reconcile-demo shows injection, dry-run, apply,
the repeat, quarantine through the API, healing, the held lock, a
stopped S3 and the run under uploads in about four minutes; the cost
matrix is evidence/reconcile/cost/summary.txt (make reconcile-cost
repeats it on a fresh stand in about seven).

The lab4-storage-reconciler spec is added and the quarantine rule of
lab4-attachments is updated in the main specs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 07:19:42 +03:00
ArtyomandClaude Opus 5.5 58cae16ef8 Report track 2 and check levels 3 and 4 after it
REPORT.md gets the track 2 section: what the reconciler does and why it
is safe, the hypotheses written before the first run, the method of the
demo and the cost matrix with its screening, both result tables, the
verdicts and the limits. H1 holds. H2 holds for the pass cost: time is
linear (t(30k)/t(10k) = 3.73, 3.05 in the series of 29.10), the listing
is 95 % of it, list requests are ceil(N/1000) and SQL one more for the
empty last keyset page, RSS stays at 82.5-83.8 MiB; --deep is 4.3-5
times dearer per object, not ten. The criteria table, the failure table,
the limits, AGENTS.md and the openspec context name the track rows, and
evidence/reconcile/README.md describes every file.

On a stand from a clean state make test, test-persistence,
test-failover, restore, reconcile, lint, check, validate and
student-test (342 passed) all pass; the dry-run after these scenarios
finds 3 objects, 3 rows and no discrepancy.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 07:19:16 +03:00
ArtyomandClaude Opus 5.5 8cb5a664c6 Keep the start allowance and retries in the cost summary
The edit that added them to the plan of the series missed after the
formatter split the line, so summary.json of df345b3 lists only the two
thresholds; that series ran with the defaults of b191623 (1.5 and 0.5
core-s, three retries). The summary of the next series records them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 06:55:50 +03:00
ArtyomandClaude Opus 5.5 df345b32e1 Record the cost of a reconciler pass up to 30k objects
make reconcile-cost on a fresh stand at b191623: RustFS 2 CPU / 3 GiB on
cpus 11-12, PostgreSQL on 13-14, the reconciler on 15, three dry-run
passes per point; no run was disturbed, foreign CPU stayed at most 0.2
cores in the VM and 0.01 on the pinned cores. Medians:

  objects  mode     t, s    lists  sql  gets  rss, MiB
     1000  shallow  0.105       1    2     0      82.5
    10000  shallow  1.000      10   11     0      83.6
    30000  shallow  3.729      30   31     0      83.8
    10000  page100  2.058     100  101     0      81.0
     1000  deep     0.493       1    2  1000      83.0
    10000  deep     5.041      10   11 10000      84.1
    30000  deep    16.150      30   31 30000      84.1

The listing takes 95 % of a shallow pass. The first full series of
29.10 (5ca2cdc, not screened, another lab under k6 at the time) is kept
in cost-2026-10-29 for comparison between days.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 06:55:45 +03:00
ArtyomandClaude Opus 5.5 b1916236f4 Record the track 2 demo on the stand
make reconcile-demo on a fresh stand at 5c3c238, 12 of 12 checks true.
The dry-run found exactly what was injected on both sides (3 stale
orphans, 3 missing objects, 3 shorter and 3 same-size rewritten objects,
6 stale intents with and without an object, 2 fresh orphans and 2 fresh
intents) and changed nothing; apply fixed the same 18 and the second
apply did nothing. The independent check outside the API found no
violation and no lost ready attachment; the 9 damaged rows sit in
quarantine with their message links, the metadata answers 200 and the
content 404, and a restored object left quarantine. A pass during a held
lock was skipped, a pass with s3 stopped exited with 1 in 1.6 s and
changed nothing. 75 apply passes during 75 s of uploads through the
balancer removed only the 10 injected leftovers, saw 247 objects of
uploads in flight as fresh orphans and kept them: all 3418 uploads are
ready with matching SHA-256.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 06:48:07 +03:00
ArtyomandClaude Opus 5.5 5c3c238d17 Screen the cost runs for foreign load and check a pass without S3
The cost matrix shares the Docker VM with the stands and builds of other
labs. Each run now reads the VM-wide /proc/stat and the cpu.stat of the
s3 and postgres cgroups before and after the pass, and the reconciler
reports its own CPU time. Foreign CPU over the window is the busy time
minus ours minus the cost of starting a container (1.5 core-s in the VM
and 0.5 on the pinned cores, measured on the idle stand). A run with
more than 2 foreign cores in the VM or 0.25 on the pinned cores goes to
cost/disturbed and is repeated after 15 s of quiet, up to three times;
docker stats of the whole host are saved before and after the series.

The demo also runs a pass with s3 stopped: it must exit with code 1 in
bounded time, log reconcile.failed and leave PostgreSQL and the bucket
as they were.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 06:35:59 +03:00
ArtyomandClaude Opus 5.5 3b3cb5bd7f End a failed reconciler pass with the dependency error
The merge loop runs inside the TaskGroup that holds the --deep checks,
so a listing or page failure in the middle of a pass left the group as
an ExceptionGroup. The entry point catches Unavailable only: the pass
still exited with code 1, but through an uncaught traceback instead of
the reconcile.failed record. The pass now unwraps the group and raises
the Unavailable with its original cause; the API test fails the listing
on the second page of a deep apply pass and expects Unavailable.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 06:31:46 +03:00
ArtyomandClaude Opus 5.5 8cd30488d2 Archive the carry over of the lab 3 fixes change
Sync the delta specs into the main specs: zones are linked by the
schema and the ports main.py assembles, the event bus and the network
dependencies name S3 and Valkey, an outsider does not wait for chat
locks, an empty cursor is rejected, a request cancelled at shutdown gets
503 in the contract format, the body limit counts received bytes per
route, logout withdraws the revocation mark on a database failure,
detection runs three times, failover-each records the stopped replica,
lost answers are retried on the stand, posting checks its input in a
fixed order and make up waits for every replica in the balancer.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 06:25:44 +03:00
ArtyomandClaude Opus 5.5 e927afdb09 Carry over the lab 3 fixes made after 61c0c28
Bring the system changes of lab 3 from 61c0c28..72a1e57 onto the lab 4
code, resolving each conflict by meaning and keeping everything lab 4
added:

- a message is posted with one SQL statement under the chat row lock,
  and the attachment links go into the same statement; a foreign key
  violation on the attachment link still answers 404 and leaves nothing
  behind. Text and the attachment list are checked before the write, an
  outsider gets 404 for both, as before the carry over;
- the request pipeline counts the body bytes actually received against
  the limit of the route, so a chunked body over 1 MiB gets 413 and the
  upload route keeps its MAX_UPLOAD_BYTES limit;
- a request cancelled at shutdown gets 503 unavailable in the contract
  format, the worker waits a second less than the rest of the shutdown
  budget, SHUTDOWN_TIMEOUT_SECONDS becomes 6 s and the stop hooks 7 s;
- readiness sits behind a Readiness port with the draining flag in
  shared infrastructure, and the drain window is logged through Logger;
- logout revokes through SessionRevocations and withdraws the mark when
  PostgreSQL rejects the delete; an empty cursor is 400;
- EventBus.project is gone, the sweep test subscribes and waits on a
  queue; domain tests check attachment_list instead of Chat.post;
- make up waits for every replica in the balancer, BASE_URL follows the
  lb port, the image is tagged by the compose project, retry-check and
  faults-evidence are added, detection runs three times, failover-each
  and rolling-update record the stand usage, CI checks numeric uids.
  down also takes the tools and reconcile profiles of lab 4.

Track 1 tooling of lab 3 (scaling.py, its samplers, tools/ and the CPU
pinning of api, lb, valkey and k6) stays out; stand-usage.sh queries the
database size itself instead of the track 1 sampler.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 06:25:23 +03:00
ArtyomandClaude Opus 5.5 7ac1a4a11b Propose carrying over the lab 3 fixes as an openspec change
Lab 4 started from the lab 3 commit 61c0c28, and lab 3 changed up to
72a1e57 after its track and two reviews. The change lists what moves
over and how it meets the lab 4 code: the one-statement message write
takes the attachment links along, the body limit counts received bytes
per route, the shutdown, readiness and logout fixes come as they are,
and the stand tooling keeps the lab 4 profiles and CPU pinning. Delta
specs bring the requirements lab 3 changed, adapted to three zones and
the object store; track 1 tooling stays out.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-30 06:15:48 +03:00
ArtyomandClaude Opus 5.5 5ca2cdc9af Measure the pass cost up to 30k objects
Filling RustFS 1.0.4 to 100k objects under one prefix did not finish in
two attempts: a write gets slower as the prefix grows (about 8 ms in an
empty prefix against 32 ms at 28k objects, 13 writes per second with 16
parallel writers), with enough memory and no background scanner load.
The cost matrix now stops at 30k objects with four parallel writers,
which still spans a factor of 30 for the linearity check; the design
and the spec of the change say so, and both aborted attempts with their
1k and 10k points and the diagnosis are kept in
evidence/reconcile/cost-aborted.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 04:40:24 +03:00
ArtyomandClaude Opus 5.5 7dca40c55e Give the balancer time to see the replicas before it counts as unhealthy
The balancer reports itself unhealthy while no replica is up, and its
start period of 10 s was shorter than the time the replicas need on a
busy host: they wait for migrate and s3-init and have a 30 s start
period of their own. docker compose up --wait then failed on a cold
start although the stand came up seconds later. A 60 s start period
with 1 s probes keeps the balancer starting, not unhealthy, until the
first replica is in rotation.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 03:52:27 +03:00
ArtyomandClaude Opus 5.5 de9dc61ebc Give RustFS room for the 100k point of the cost matrix
The first cost run stalled while filling the bucket to 100k objects:
RustFS keeps object metadata in memory, at about 45k objects it hit
its 1 GiB limit, the cgroup kept reclaiming and PutObject slowed from
about 240 to 11 objects per second. The S3 CPU limit is now taken from
S3_CPUS (default 1, as before), and the cost run gives RustFS 2 pinned
CPUs and 3 GiB for every point, so all N are measured with the same
limits; seeding uses 16 parallel writes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 03:50:30 +03:00
ArtyomandClaude Opus 5.5 a335f654ed Add the track 2 fault injection, invariant check and experiment driver
reconcile-inject.sh and reconcile_check.py come from the prepared kit:
the first breaks either side on purpose (an object without a row, a
removed object, another size, the same size with other bytes, an old
intent with and without its object), the second is an oracle outside
the API that classifies every row and object from psql and rc, hashes
objects with --deep and reports ready attachments lost against a saved
set.

reconcile_track.py demo uploads through the balancer, links some
attachments to messages, injects each class on both sides with old and
fresh variants, and checks that a deep dry-run finds exactly what was
injected and changes nothing, that apply fixes exactly that and a
second apply does nothing, that broken rows and their message links
survive in quarantine with metadata 200 and content 404, that a
restored object heals, that a second pass is skipped while the lock is
held, and that passes in a loop during 75 s of uploads lose nothing.
Intents are injected 300 s old, between the reconciler grace and the
API sweep grace, so only the reconciler removes them.

reconcile_track.py cost snapshots docker stats of the whole host, pins
S3, PostgreSQL and the reconciler to their own CPUs, fills the stand to
each N with seed_storage.py run in the API image (parallel PutObject and
COPY), and records three dry runs per N and mode with a median table.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 03:23:59 +03:00
ArtyomandClaude Opus 5.5 51fa19a8ee Run the reconciler as a one-off service of the stand
The reconciler service under the reconcile profile runs the API image
with the reconciler module as entrypoint and --dry-run as the default
command, so docker compose run --rm --no-deps reconciler takes only
flags. It gets the database URL and the limited API key of S3, which
already allows listing, reading and deleting objects, a read-only root,
1 CPU and 256 MiB, and a longer S3 read timeout for listing pages.
S3, PostgreSQL and the reconciler accept an optional cpuset from the
environment so measurements can pin them; the default is no pinning.

make reconcile ARGS=... runs a pass, make reconcile-demo and make
reconcile-cost drive the track experiments, and the limits policy now
covers the new service.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 03:17:54 +03:00
ArtyomandClaude Opus 5.5 91731fd317 Reconcile attachment metadata with the bucket in one merge pass
StorageReconciler walks the sorted bucket listing and keyset pages of
attachments ordered by object key side by side, so a pass is linear
and keeps one page of each side in memory. An object without a row is
deleted only when it is older than grace plus skew and a lookup by key
right before the delete still finds no row; a ready row whose object
is missing, has another size or, with the deep check, another digest
is put in quarantine after a HEAD recheck and is never deleted; a stale
intent is claimed with SKIP LOCKED and dropped object first; a
quarantined row whose object matches again is released. Deep checks
hash objects in a bounded task group, each action uses its own unit of
work, and failures of single actions are counted instead of aborting.
An advisory lock lets one pass run at a time. Content of a quarantined
attachment answers 404 without touching S3, its metadata is unchanged.

The storage port gains listing pages and HEAD, the repository keyset
pages, lookup by key, claim and quarantine marking; the platform logger
can write to another stream. The one-off entry point
python -m messenger.attachments.entrypoints.reconcile is a dry run
unless --apply is given, assembles the adapters with the API key of S3
and prints a JSON report with counts per class, samples and the cost
of the pass to stdout while the journal goes to stderr.

Tests run the reconciler against its own migrated database with every
class, apply and repeat, the row that appears after the listing, the
busy lock and the release, and check paged byte-order listing and HEAD
against RustFS.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 03:12:10 +03:00
ArtyomandClaude Opus 5.5 62986245a2 Add the quarantine columns for the storage reconciler
Migration 0004 adds a nullable quarantine reason (missing, size or
digest mismatch) and the time it was set, both null or both present.
Nullable columns without a default only touch the catalogue, so the
running version keeps working while the migration is applied.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 03:11:59 +03:00
ArtyomandClaude Opus 5.5 148868bdfb Propose the storage reconciler as an openspec change
Track 2 of grade 5: a one-off reconciler that merges the sorted bucket
listing with keyset pages of the attachments table, so a pass is linear
in time and holds one page per side in memory. It finds objects without
a row, ready rows without an object or with another size or digest, and
abandoned intents; by default it only reports, with --apply it deletes
old orphans after a row recheck, drops stale intents object first, and
quarantines broken ready rows instead of deleting them, so referenced
attachments survive and a restored object heals. A quarantined
attachment answers 404 on its content. An advisory lock keeps a single
pass at a time.

The design states the hypotheses on correctness and on the cost of a
pass, the reproducible method behind make reconcile-demo and make
reconcile-cost, and the acceptance criteria.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 03:05:42 +03:00
ArtyomandClaude Opus 5.5 d2744bc1ac Archive the upload resilience change
Grade 4 of lab 4 is closed. A failed ready commit after the object
write is compensated at once under a row lock, intents abandoned by a
crash or a lost write are swept with their objects after a 900 s grace
period by every replica with SKIP LOCKED, and nothing younger, nothing
ready and nothing referenced is touched. A client abort is a 400 and a
stalled body a 503 after 8 s, both leaving nothing behind. Three upload
slots per worker, capped socket buffers in the balancer and the API
and a fixed glibc mmap threshold keep 40 concurrent 10 MiB uploads at
330 of 512 MiB per replica with every upload succeeding, while without
the slots the same load hits the limit and loses 37 of 80. 36 user
errors through the balancer give no 5xx, and 23 checks prove the
bucket private, the API key limited, the console closed and the
bootstrap idempotent.

For the defence: run make upload-faults to show the negative suite,
the compensation, the killed replica with its leftover swept after the
grace period while the fresh one stays, and the abort and stall; show
the memory summary and make s3-check.

The lab4-upload-resilience spec is added, and the write order of
lab4-attachments and the console and API key requirements of
lab4-object-storage are updated in the main specs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 00:25:46 +03:00
ArtyomandClaude Opus 5.5 2b19277b1e Record level 4 evidence and fill in the report
Evidence comes from the running stand at a774a2f: upload-faults.txt
with the negative suite through the balancer (36 user errors, no 5xx
in the replica logs) and the compensation, crash, sweep, abort and
stall checks; upload-memory with per-run JSON and a summary for 64
and 3 slots, 1 and 10 MiB and 10, 20 and 40 concurrent uploads plus
the mmap threshold comparison; s3-security.txt with 23 checks; and
regression-level4.txt showing that smoke, persistence, failover of
each replica, the upload failover, S3 outage and abort scenarios, the
limits policy and all 15 stand checks still pass. The lint and own
test log now counts 335 tests. The upload-faults target stamps its
output with the date and commit.

REPORT.md gains rows 4.1 to 4.4 and a regression row, the compensation
and sweep mechanism with its grace period, where each upload limit and
buffer cap applies, the new variables, level 4 failure rows and the
memory experiment with hypothesis, method, results and limits. AGENTS
lists the new targets.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 00:24:41 +03:00
ArtyomandClaude Opus 5.5 a774a2fbbd Measure upload memory and bound the buffers along the chain
upload_memory.py recreates the replicas and the balancer for every run
of 10, 20 and 40 concurrent uploads of 1 and 10 MiB with 64 slots
(effectively no limit) and with 3, drives them through lab4_seed.py
from the prepared tooling, and keeps per-run JSON plus a summary with
the cgroup memory.peak of each replica and of the balancer and the
oom_kill counters. The seed script now also records memory.current
before the load and reads X-Instance-Id regardless of case.

The first run showed that slots alone only move a waiting body out of
the worker: with 3 slots and 40 uploads of 10 MiB the kernel grew the
socket buffers of HAProxy to about 110 MB and the 128 MiB balancer was
killed. HAProxy now caps its client and server socket buffers at 64
KiB and the API replicas cap tcp_rmem and tcp_wmem at 256 KiB, which
keeps the balancer at 30 MiB. glibc raised its mmap threshold after
the first large free and kept freed 10 MiB bodies in the heap, so the
API fixes MALLOC_MMAP_THRESHOLD_ at 128 KiB.

With these settings 40 concurrent uploads of 10 MiB peak at 323 MiB of
512 per replica and all 80 succeed, while without the slot limit the
same load reaches 512 MiB, a worker is killed and only 31 of 80
succeed. UPLOAD_CONCURRENCY stays at 3.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-29 00:14:09 +03:00
ArtyomandClaude Opus 5.5 98df351235 Check upload faults and user errors against the stand
test_attachment_faults.py runs through the balancer against the real
PostgreSQL and RustFS. The negative suite sends a body one byte over
the limit with Content-Length (answered before any body byte) and
chunked, a decompression bomb, truncated and disguised images, missing
and foreign content types, dangerous names, a stranger's reads and
references, an attachment of another chat and invalid lists, checks
each code and error body, and finds no 5xx in the replica logs and no
extra rows.

Faults come from triggers installed for the module and dropped after
it: an AFTER INSERT trigger remembers the id and key of each fault
intent, a BEFORE UPDATE trigger rejects the ready commit for
fault-fail names and holds it for 1.8 s for fault-crash names, while
the test finds the waiting backend's client address and kills that
replica with SIGKILL. The rejected commit leaves neither row nor
object right away and an audit line says compensation; a crash leaves
a pending row and an object, the one aged past the grace period is
swept with its object while the fresh one stays, and an aged ready
attachment in a message still downloads. A body cut after 256 KiB is
logged as 400 with nothing written, and a stalled body gets 503 after
8 s with nothing written.

make upload-faults stores the output in evidence/upload-faults.txt
without tracebacks of locals, and the CI acceptance job runs it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-28 22:48:46 +03:00
ArtyomandClaude Opus 5.5 28055a8551 Pass the upload limits to the API and check the console from the network
The API replicas get UPLOAD_CONCURRENCY, UPLOAD_GRACE_SECONDS,
UPLOAD_SWEEP_INTERVAL_SECONDS and UPLOAD_SWEEP_BATCH through the S3
anchor of compose.yaml with the same defaults as the settings, and
.env.example documents them. A value in the shell overrides the
default, which the memory experiment uses to recreate the replicas with
a different number of slots.

s3-check.sh now also asks the console port of the S3 service from a
separate container on the stand network and expects a refused
connection, so 23 checks cover ports, the console inside and outside
the container, the repeated bootstrap, the rights of the API key and
anonymous access.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-28 22:40:56 +03:00
ArtyomandClaude Opus 5.5 0e4eb1738c Compensate failed uploads and sweep abandoned intents
When the ready commit fails after the object was written, the upload
handler now locks the row, keeps it if it turned out ready, and
otherwise deletes the object first and the pending row second before
answering 503. A ready update that touches no row means the intent was
already swept, so it fails as unavailable and the object goes too;
a 201 without a row cannot happen.

Every worker runs an UploadSweeper that every 30 s removes pending
intents older than UPLOAD_GRACE_SECONDS (900 s, at least 60 s) one row
at a time under FOR UPDATE SKIP LOCKED over the partial pending index,
object first, and logs an audit event for each discard. Bodies are
buffered only inside one of UPLOAD_CONCURRENCY slots per worker and
released before the ready commit, and a client that disconnects in the
middle of a body becomes a 400 instead of an unhandled 500.

The tests run against a throwaway PostgreSQL: a trigger rejects the
ready commit and the compensation leaves neither row nor object, a
row removed during the write gives 503, a failed write stays until the
grace ends, fresh intents and an aged ready attachment in a message
survive a sweep, two concurrent sweeps share five intents exactly, the
background loop runs by itself, a second upload waits for the slot
without reading its body, and aborted and stalled bodies leave nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-28 22:39:51 +03:00
ArtyomandClaude Opus 5.5 70a0c6065e Keep events of committed transactions in multi-step commands
A command may now run several transactions: the upload compensation
commits a removal after the ready commit failed, and a sweep commits
one removal per abandoned intent and ends with a rolled back lookup.
The unit of work cleared every collected event on any rollback, and the
command bus published nothing when the handler raised, so the audit
trail lost discards that had really been committed.

A rollback now drops only the events recorded inside that transaction,
and the bus publishes what was collected even when the handler fails.
Events still come only from committed transactions.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-28 22:39:31 +03:00
ArtyomandClaude Opus 5.5 a41580aceb Propose upload resilience as an openspec change
Grade 4 of lab 4 asks that a failure between the S3 write and the
PostgreSQL commit leaves no eternal orphans, that concurrent uploads
cannot take unbounded memory, that user errors never become a 500 and
that the API key and the private bucket are proven limited outside the
API. The change compensates a failed ready commit right away under a
row lock, sweeps abandoned intents after a grace period in every
replica with SKIP LOCKED, maps a client abort to a client error, bounds
buffered bodies per worker with upload slots, and checks all of it
against the stand: a negative suite through the balancer, faults
injected with a PostgreSQL trigger and a killed replica, and a memory
experiment with 10, 20 and 40 concurrent uploads.

The new lab4-upload-resilience capability holds these requirements;
the write order of lab4-attachments and the console and key checks of
lab4-object-storage are updated by deltas.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-28 22:34:39 +03:00
ArtyomandClaude Opus 5.5 e4253eb076 Archive the image attachments change
Grade 3 of lab 4 is closed. RustFS with a private bucket runs in the
stand, metadata lives in PostgreSQL and the bytes only in the bucket,
uploads answer 201 ready after the object write and the commit, and
the original is served byte for byte to chat members only. The smoke
test passes from a fresh clone; limits of 10 MiB and 40 MP, content
type by content and dangerous names are covered by 325 own tests; an
upload survives the stop of the replica that took it, both replicas
fail over under writes in under 3.1 s, a full restart keeps metadata
and bytes, and with S3 stopped uploads and downloads answer 503 within
2.6 s while texts, metadata and readiness keep working. 22 checks show
the bucket is private outside the API and the API key is limited.

For the defence: upload the fixture, send it in a message, download it
as the second member and compare SHA-256, get 404 as a stranger and
403 for an anonymous GET in S3, then run persistence, failover and the
upload failover scenario.

The lab4-attachments and lab4-object-storage specs are added, and
message sending, history, idempotent replay, the restart hook and stand
persistence are updated in the main specs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 22:20:38 +03:00
ArtyomandClaude Opus 5.5 db901d6401 Record level 3 evidence and fill in the report
Evidence comes from the stand started from an empty state and from a
fresh clone: the public smoke, the contract checks, lint and 325 own
tests, the storage layout with an out-of-API comparison of a stored
object against its metadata, failover of each replica under writes, the
upload failover scenario, persistence with StartedAt of every service
including S3, the S3 outage scenario and 22 S3 privacy and bootstrap
checks. The storage evidence script now covers the attachment tables
and the S3 secrets.

REPORT.md follows the lab 4 template: launch from a clean clone,
architecture with the source of truth for each fact, the write order
between PostgreSQL and S3 and what each failure leaves behind, where
each upload limit applies, roles and services, the .env.example
mapping, grade 3 rows and the grade 3 failure table. The design notes
the botocore Expect header that hung uploads behind the port proxy.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 22:20:10 +03:00
ArtyomandClaude Opus 5.5 24f9d6195b Add the attachment failure scenarios and S3 checks
lab4_scenarios.py drives the public contract through tests/client.py:
failover-upload stops the replica that answered the upload with the
stop-one hook and downloads through another one comparing SHA-256, and
s3-outage stops S3 and records status and time of upload, download,
metadata, a text message and readiness before bringing it back. Both
print JSON with an ok field. s3-check.sh checks published ports, the
console, two more bootstrap runs without state changes, the allowed
and denied operations of the API key and anonymous access including a
plain HTTP GET from a separate container. evidence-attachments.sh
shows where the bytes live and compares a stored object with its
metadata outside the API.

Makefile gains scenario, s3-check and attachments-evidence, ruff covers
the new script, and the CI acceptance job runs both scenarios and the
S3 check after the smoke test.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:50:03 +03:00
ArtyomandClaude Opus 5.5 5aa766acff Run RustFS with a private bucket in the stand
MinIO community images can no longer be pulled on this arm64 host, so
the stand runs RustFS 1.0.4 pinned by digest as non-root with a read
only root, no published port, the console off and data on the s3data
volume. A one-off s3-init with rc v0.1.36 creates the bucket, keeps it
private for anonymous clients, creates the API user with a policy on
the objects and listing of that one bucket, imports a lifecycle rule
for incomplete multipart uploads and checks itself; the API replicas
start only after it succeeded. Root keys reach only s3, s3-init and the
operator s3-cli; the API gets its own key and the S3 settings through
an anchor merged into its environment.

secrets.sh creates hex S3 keys, the restart hook restarts S3 next to
PostgreSQL and Valkey and waits until it is healthy, the limits policy
covers the S3 services, and the stack evidence lists the new packages.
The object storage adapter is tested against a throwaway RustFS of the
same image: a 10 MiB round trip, a missing object, an idempotent delete
and an unreachable endpoint failing within the request budget.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:50:03 +03:00
ArtyomandClaude Opus 5.5 f9760fc098 Link messages to attachments of the same chat
A message now carries attachment_ids in the request, in every response,
in the idempotent replay and in history, in the order they were sent.
The chat aggregate checks membership first, then refuses whitespace
text, more than ten or repeated attachments, and an empty text without
attachments, so an outsider still gets 404 before any 400.

The send statement inserts the links next to the message and the
idempotency key, and the foreign key from message_attachments to
attachments of the same chat turns an unknown or foreign attachment
into 404 and rolls the whole send back, without the messaging zone
reading the attachments table. Replay and history read the list with a
subquery on the primary key. The request fingerprint covers the list,
so a missing attachment_ids and [] are the same body while a different
order is a conflict.

The zone dependency test now covers three zones, and the SQL ownership
test checks that every zone touches only its own tables.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:45:19 +03:00
ArtyomandClaude Opus 5.5 00826a40d3 Serve attachment upload, metadata and download through the API
Add the adapters behind the attachments ports: PostgreSQL for the
pending and ready rows, with a foreign key violation on the chat member
turned into 404; Pillow that opens only PNG and JPEG, refuses a type
that differs from Content-Type, checks the pixel count from the header
before any decoding, verifies PNG chunks and decodes JPEG at 1/8 scale
in a worker thread under a semaphore; and S3 on aiobotocore with path
style, SigV4, short timeouts and checksums only when required. botocore
sends Expect: 100-continue for streamed bodies and RustFS behind the
Docker port proxy never answers it, so the PUT hung until the read
timeout; the handler that adds the header is unregistered.

The HTTP layer streams the raw body into the use case, returns the
contract Attachment and streams the original back with its content
type and length and no redirect. The request pipeline takes a body
limit per route, so uploads may carry 10 MiB while JSON stays at 1 MiB.
main.py wires the zone and answers its membership port from the
messaging chat directory.

Tests run the API with an in-memory object store: download by another
member, 404 for strangers, the exact 10 MiB limit and one byte over it
with Content-Length and chunked, 40 MP and above, spoofed and truncated
images, unsupported types, dangerous names, the variant, a failing
store and a lost object.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:44:32 +03:00
ArtyomandClaude Opus 5.5 76c9673ab3 Add the attachments zone with its domain and use cases
The zone owns the Attachment aggregate, which is staged as pending with
a server-assigned object key and becomes ready only when stored, the
Filename value that refuses empty, blank, overlong names and names with
a path separator or a control character, and the declared image type.

UploadAttachment checks membership first through the ChatMembership
port, then the name and the declared type, reads the body stream only
up to the limit while hashing it, inspects the image through a port,
commits the pending row, writes the object through the ObjectStorage
port and commits the ready row. GetAttachment and OpenAttachment answer
404 to strangers and to a ready row whose object is gone.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:43:41 +03:00
ArtyomandClaude Opus 5.5 3794df20d4 Add the attachments schema as an additive migration
Migration 0003 creates attachments with a pending or ready status, a
server-assigned object key in byte order collation and a partial index
for pending rows, and message_attachments that keeps the order of the
attachments of a message. Foreign keys hold the links between zones:
an attachment belongs to a member of its chat, and a message may only
reference an attachment of its own chat, with RESTRICT so a referenced
attachment can never be deleted. The text check is relaxed to at most
4000 code points because an empty text is legal next to an attachment;
an empty message without attachments is still refused by the domain.

The migration test covers the new version, a rerun without changes and
both foreign keys.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:25:35 +03:00
ArtyomandClaude Opus 5.5 d7fb96bb70 Propose image attachments as an openspec change
Plan grade 3 of lab 4 as one change: a third domain zone for
attachments that takes the raw bytes of one PNG or JPEG, applies the
size limit before reading the whole body and the pixel limit before
decoding, checks the type by content, writes a pending row, the object
and then the ready row and only then answers 201, and serves metadata
and the original only to chat members through the API. Messages gain
attachment_ids, linked by a foreign key to attachments of the same chat
so the messaging zone never reads the attachments table, and the zone
asks messaging about membership through a port wired in main.py.

The stand gains RustFS with a private bucket, a one-off bootstrap with
a separate API key, and a restart hook that waits for S3. The specs add
lab4-attachments and lab4-object-storage and modify message sending,
history, idempotent replay, the restart hook and stand persistence.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:24:19 +03:00
ArtyomandClaude Opus 5.5 bf8e4e3cd1 Carry over the lab 3 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy and k6 configuration, migrations, hooks, evidence and level 4
scripts and the CI job from the lab 3 solution commit 61c0c28, merge
the lab 3 Makefile targets into the lab 4 skeleton Makefile without
touching its targets, and append the lab 3 solution variables to the
skeleton .env.example. The package and the application follow the
contract version 1.4.0, and the image and the throwaway test containers
are tagged lab4 so they do not collide with a lab 3 stand on the same
host.

This is the starting point of the lab 4 cycle: lint, own tests and the
offline skeleton check pass before any lab 4 change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:17:51 +03:00
ArtyomandClaude Opus 5.5 b0f463ac5c Carry over the agent context and openspec history from lab 3
Bring the Claude Code settings, the lint hook, the opsx commands and
skills, the architecture notes, the lab 1 to lab 3 specs and the
archived lab 1 to lab 3 changes into the lab 4 skeleton, so lab 4
continues the same spec history instead of starting from scratch. The
files come from the lab 3 solution commit 61c0c28.

Rewrite AGENTS.md and the openspec context and rules for lab 4: image
attachments with metadata in PostgreSQL and bytes in a private RustFS
bucket inside the stand, a third domain zone for attachments that asks
the messaging zone about chat membership through a port wired in
main.py, upload limits applied before unbounded reading or decoding,
201 only after both the object write and the commit, Out of scope moved
to labs 5-7 plus presigned uploads, and rules on the write order between
the two stores and on root S3 keys staying out of the API.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:16:50 +03:00
Mikhail Verkovykh 65003b6119 Подготовить skeleton лабораторной 2 по мессенджеру 2026-09-10 18:01:35 +03:00
Mikhail Verkovykh ec540a1a72 Подготовить skeleton лабораторной 4 по мессенджеру 2026-09-10 18:01:35 +03:00
vmd 4c14ccbadd Первый коммит 2026-09-10 17:39:58 +03:00
942 changed files with 46958 additions and 36113 deletions
+2 -23
View File
@@ -18,17 +18,12 @@ S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000
BROKER_URL_FILE=/run/secrets/broker_url
WORKER_CONCURRENCY=2
JOB_MAX_ATTEMPTS=5
JOB_TIMEOUT_SECONDS=60
STAGING_RETENTION_SECONDS=86400
# Solution-specific: published LB ports, replica limits, workers and pool per replica,
# LB queue per replica, drain window before closing the listener on SIGTERM, PostgreSQL
# limits, load generator limits (profile bench), cursor key file. API_PORT/SHORTTTL_PORT of lab2 are gone:
# only the load balancer is published.
LB_HTTP_PORT=18085
LB_STATS_PORT=25085
LB_HTTP_PORT=8080
LB_STATS_PORT=8404
API_CPUS=1
API_MEMORY=512m
WEB_CONCURRENCY=2
@@ -55,22 +50,6 @@ UPLOAD_SWEEP_INTERVAL_SECONDS=30
UPLOAD_SWEEP_BATCH=100
# Fixed glibc mmap threshold for the API: buffers above 128 KiB are returned to the system on free.
MALLOC_MMAP_THRESHOLD_=131072
# Solution-specific for lab5: RabbitMQ management UI on 127.0.0.1, backoff base of a transient
# retry (doubles per attempt up to 60 s), relay poll and sweep intervals, worker limits and the
# PostgreSQL pool of relay and worker. FAULT_POINT is set only by infra/compose.faults.yaml.
BROKER_MANAGEMENT_PORT=25086
JOB_BACKOFF_BASE_SECONDS=2
OUTBOX_POLL_SECONDS=1
SWEEP_INTERVAL_SECONDS=5
WORKER_CPUS=2
WORKER_MEMORY=1g
PIPELINE_DB_POOL_MAX_SIZE=4
# Solution-specific for lab5 grade 4: render time per job (the render process is killed after it),
# address space of one render process (WORKER_MEMORY >= WORKER_CONCURRENCY * RENDER_MEMORY_MB plus
# ~120 MiB of the worker itself), jobs per render process before it is replaced.
RENDER_TIMEOUT_SECONDS=30
RENDER_MEMORY_MB=448
RENDER_TASKS_PER_CHILD=100
# Minimal client transfer rate, bytes/s: every body byte moved in either direction extends the
# request deadline by 1/rate, so slow but steady uploads and downloads outlive REQUEST_TIMEOUT_SECONDS.
MIN_TRANSFER_RATE_BYTES=131072
+1 -1
View File
@@ -1,4 +1,4 @@
## Лабораторная 5
## Лабораторная 4
Автор / группа: TODO
Целевая оценка (3/4/5): TODO
+2 -23
View File
@@ -19,7 +19,7 @@ jobs:
- run: make student-test VENV=.venv
acceptance:
name: Стенд Compose с RabbitMQ, relay и worker за HAProxy, smoke, pipeline, отказ реплики, рестарт и отказы зависимостей
name: Стенд Compose с RustFS за HAProxy, smoke, вложения, отказ реплики, рестарт и отказы зависимостей
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -34,17 +34,6 @@ jobs:
- name: Публичный smoke через балансировщик
run: make test
- name: Топология брокера, consumer с prefetch и права клиентов
run: make topology
- name: Уровни «3» и «4» pipeline — worker остановлен, рестарт брокера, дубль, S3, попытки, варианты и пределы, падения в окнах 2–5, аренда, replay, DLQ, jitter, retention
run: |
make suite-preflight
make level4
- name: Сообщение задания в очереди, 409 до ready и SIGTERM relay и worker
run: make pipeline-evidence
- name: Вложение после остановки принявшей его реплики и при недоступном S3
run: |
make scenario SCENARIO=failover-upload
@@ -82,8 +71,7 @@ jobs:
- name: Наружу опубликован только балансировщик
run: |
docker compose ps --format '{{.Service}} {{.Ports}}' | awk '$2 != "" && $1 != "lb" && $1 != "broker" {print; bad=1} END {exit bad}'
docker compose ps --format '{{.Service}} {{.Ports}}' | awk '$1 == "broker" && $2 !~ /^127\.0\.0\.1:/ {print; bad=1} END {exit bad}'
docker compose ps --format '{{.Service}} {{.Ports}}' | awk '$2 != "" && $1 != "lb" {print; bad=1} END {exit bad}'
- name: Процессы работают не от root
run: |
@@ -99,15 +87,6 @@ jobs:
case "${user%%:*}" in ""|0|root) exit 1 ;; esac
done
- name: Корректная остановка relay и worker по SIGTERM
run: |
start=$(date +%s)
docker compose stop -t 10 relay worker
elapsed=$(( $(date +%s) - start ))
codes=$(docker inspect -f '{{.State.ExitCode}}' $(docker compose ps -aq relay worker) | sort -u)
echo "остановка за ${elapsed} с, коды завершения ${codes}"
test "$elapsed" -le 10 && test "$codes" = "0"
- name: Корректная остановка реплик API по SIGTERM
run: |
start=$(date +%s)
+52 -33
View File
@@ -1,63 +1,82 @@
## Что это за репозиторий
Skeleton лабораторной 5 курса «Мессенджер под нагрузкой» (МТУСИ, 7 независимых лаб) и решение в ветке `solution/bpi2303-kostylev`. Skeleton даёт задание (`README.md`), нормативный контракт (`contracts/`) и публичные black-box проверки (`tests/`). Реализация API, worker, relay, Dockerfile, compose-стенд, конфигурация балансировщика, S3 и брокера, миграции, хуки отказов и собственные тесты — студенческие; решение лабы 5 построено переносом решения лабы 4.
Skeleton лабораторной 4 курса «Мессенджер под нагрузкой» (МТУСИ, 7 независимых лаб) и решение в ветке `solution/bpi2303-kostylev`. Skeleton даёт задание (`README.md`), нормативный контракт (`contracts/`) и публичные black-box проверки (`tests/`). Реализация API, Dockerfile, compose-стенд, конфигурация балансировщика и S3, миграции, хуки отказов и собственные тесты — студенческие; решение лабы 4 построено переносом решения лабы 3.
Лаба 5: приём вложения отделён от тяжёлой обработки. `POST /api/v1/chats/{chat_id}/attachments` проверяет файл как в лабе 4, кладёт оригинал в приватный префикс `staging/` bucket **RustFS** и одной транзакцией PostgreSQL фиксирует вложение `queued`, задание (`jobs`) и строку **transactional outbox**; только после этого отвечает `202` со снимком `queued`. Отдельный сервис `relay` публикует outbox в **RabbitMQ 4.1** (quorum queue, DLX, publisher confirms, `mandatory`, persistent), отдельный сервис `worker` (тот же образ, свой entrypoint) потребляет очередь через **FastStream** поверх aio-pika с ручным `ack` строго после `COMMIT` результата, захватывает задание арендой (`lease_token`), публикует оригинал в `originals/` и строит варианты Pillow. Источник истины состояний — PostgreSQL, брокер — транспорт и будильник. Остаётся всё из лаб 1–4: HAProxy перед ≥2 репликами, `X-Instance-Id`, `Idempotency-Key`, Basic → Bearer, хуки остановки реплики и рестарта стенда.
Лаба 4: вложения-изображения в сообщениях. Метаданные вложений живут в PostgreSQL, байты — в приватном bucket S3-совместимого хранилища **RustFS** внутри стенда, а не в БД и не на диске реплики. `POST /api/v1/chats/{chat_id}/attachments` принимает сырые байты одного PNG/JPEG (≤10 MiB, ≤40 млн пикселей, тип по содержимому) и отвечает `201 ready` только после записи объекта и фиксации метаданных; скачивание идёт только через API участникам чата. Сообщение несёт `attachment_ids`. Остаётся всё из лабы 3: HAProxy перед ≥2 репликами, `X-Instance-Id`, обязательный `Idempotency-Key`, хуки остановки реплики и рестарта стенда.
## Команды
```sh
make check # offline: структура skeleton, JSON, локальные $ref, синтаксис Python, версия 1.5.0
make validate PYTHON=.venv/bin/python # полная валидация OpenAPI 3.1 и jobs.schema.json (venv с requirements-dev.txt)
make check # offline: структура skeleton, JSON, локальные $ref, синтаксис Python, версия 1.4.0
make validate # полная валидация OpenAPI 3.1: openapi-spec-validator из .venv (make install); PYTHON= — свой интерпретатор
make install # uv sync --group dev
make lint # ruff check + ruff format --check + ty check; обязательно перед commit
make student-test # собственные тесты (одноразовые PostgreSQL, Valkey, RustFS и RabbitMQ в Docker)
make student-test # собственные тесты (поднимают одноразовые PostgreSQL, Valkey и RustFS в Docker)
make student-test PYTEST_ARGS='-v -k drain' # выборка тестов с именами
make secrets # локальные secrets/* (PostgreSQL, Valkey, S3 root/API/worker, RabbitMQ) и .env
make up # docker compose build, затем up -d --wait (relay и worker пересоздаются на новом образе): хранилища и broker → migrate, s3-init → api ×2, relay, worker → lb
make test # публичный smoke через LB (BASE_URL, по умолчанию http://localhost:8080)
make test-persistence ACTION_SCRIPT=scripts/restart.sh # рестарт lb, api, relay, worker и postgres, valkey, s3, broker с volumes
make secrets # локальные secrets/* (включая root и API-ключи S3) и .env из .env.example
make up # docker compose up -d --build --wait: postgres, valkey, s3 → migrate, s3-init → api ×2 → lb; затем ждёт все реплики UP в LB
make test # публичный smoke через LB (BASE_URL по умолчанию — docker compose port lb 8080, без стенда http://localhost:8080)
make test-persistence ACTION_SCRIPT=scripts/restart.sh # рестарт lb, api, postgres, valkey, s3 с сохранением volumes
make test-failover ACTION_SCRIPT=scripts/stop-one.sh # остановка реплики TARGET_INSTANCE_ID под запросами
make test-faults # тесты стенда через LB (make faults-evidence → evidence/faults.txt)
make restore # вернуть остановленные реплики и дождаться их в ротации LB
make worker-stop / worker-start # демонстрация «worker недоступен»
make queues # очереди брокера: ready, unacked, consumers
make level3 # сценарии уровня «3» suite (scripts/pipeline_suite.py) → evidence/level3.json
make level4 # сценарии уровней «3» и «4» suite и инварианты → evidence/level4.json
make failed / make replay ID=… / make dlq # реестр failed, явный replay, просмотр DLQ (python -m messenger.admin, rabbitmqadmin)
make down # остановка без удаления данных; make reset-data — намеренное удаление volumes
make limits # лимиты, порты, секреты, volumes и сети всех сервисов против политики → evidence/limits.txt
make lb-check # один токен на обеих репликах и 20 гонок одного Idempotency-Key через LB
make retry-check # потерянный ответ (запись ждёт блокировку чата) на живой и на убитой реплике, повтор тем же ключом
make scenario SCENARIO=failover-upload # upload → стоп обслужившей реплики → download через другую, SHA-256
make scenario SCENARIO=s3-outage # S3 остановлен: upload/download 503, тексты работают
make s3-check # приватный bucket вне API, ограниченные ключи API и сверки, консоль, повторный bootstrap
make upload-faults # «4»: негативный suite через LB, компенсация, уборка после grace, обрыв и зависание тела
make upload-memory ARGS='--out evidence/upload-memory/run1' # «4»: пик памяти реплик и LB при 10/20/40 загрузках 1 и 10 MiB
make load-evidence # tests/load.py ×3 клиентом-контейнером в сети edge → evidence/load.txt, evidence/load/
make overload-leftovers # после upload-memory: намерения от 503, сверка и уборка после grace → evidence/overload-leftovers.txt
make clean-clone-evidence # блок «Запуск из чистого clone» REPORT.md в свежем клоне рядом → evidence/clean-clone.txt
make reconcile ARGS="--apply" # трек 2: сверка PostgreSQL ↔ S3 (без ARGS — dry-run), one-off сервис reconciler
make reconcile-demo # трек 2: внедрение ошибок, dry-run/apply/повтор, безопасность, нагрузка → evidence/reconcile/
make reconcile-cost # трек 2: стоимость обхода 1k/10k/30k/100k × 3 (чистый стенд) → evidence/reconcile/cost/
make down # остановка без удаления данных (с профилями bench, tools, reconcile)
```
`tests/*.py` и `scripts/*.py` — только stdlib, синтаксис Python 3.9 (`make check` разбирает их системным `python3`). Проверки сами не поднимают стенд. Хуки `scripts/stop-one.sh` и `scripts/restart.sh` запускаются тестом без shell, поэтому исполняемые и с shebang. Данные не удаляются автоматически: каждый прогон smoke создаёт новых синтетических пользователей и вложения.
## Архитектура skeleton
- `lab.json` — единственный источник номера лабы (5). От него зависят `scripts/check_contract.py` (`info.version == 1.5.0`) и `tests/client.py` (ветки `LAB>=5`: upload отвечает `202 queued`, сообщение с вложением сразу, ожидание `ready` до 60 с от второго участника, ровно один вариант `thumbnail` 256×160 настоящим JPEG).
- `tests/` байт в байт как в лабе 4; поведение переключает только `lab.json`. `tests/resilience.py` после хука рестарта запрашивает метаданные и оригинал один раз с таймаутом 2 с.
- `contracts/jobs.schema.json` — формат сообщения брокера (7 обязательных полей, без bytes, URL, ключей S3 и filename); `contracts/attachment-states.md` — машина состояний и окна отказа.
- `contracts/infrastructure.json` — роли `api`, `postgres`, `load_balancer`, `s3`, `broker` (persistent volume, at-least-once), `worker` (отдельный процесс). `compose.example.yaml` — только worksheet ролей.
- `lab.json` — единственный источник номера лабы (4). От него зависят `scripts/check_contract.py` (`info.version == 1.4.0`, путь `/api/v1/attachments/{attachment_id}`, `X-Instance-Id` во всех ответах) и `tests/client.py` (ветки `LAB>=4`: upload `tests/fixtures/sample.png`, сообщение с `attachment_ids`, скачивание вторым участником, `404` постороннему).
- `tests/client.py` шлёт `Accept: application/json` на каждый запрос, включая скачивание картинки, и считает любой `30x` ошибкой: content negotiation и redirect на S3 не делаются.
- `tests/resilience.py`: перед хуком загружается `sample.png`; после `persistence` метаданные и `/content` запрашиваются **один раз** без повторов с таймаутом 2 с, поэтому хук рестарта ждёт здоровья S3. В `failover` `TARGET_INSTANCE_ID` — реплика, обслужившая первое **сообщение**, а не upload; остановку реплики, принявшей upload, доказывает `scripts/lab4_scenarios.py failover-upload`.
- `contracts/infrastructure.json` — роли `api` (≥2, без локального состояния), `postgres` (метаданные, persistent volume), `load_balancer`, `s3` (приватный bucket, persistent volume), опциональный `redis_or_valkey`. `compose.example.yaml` — только worksheet ролей.
## Ключевые правила контракта (lab5)
## Ключевые правила контракта (lab4)
- Upload: те же лимиты и коды, что в лабе 4 (`413`, `415`, `400`, `404`), но успех — `202 Attachment` со снимком `status=queued`, `variants=[]`, `error_code=null`; снимок берётся из записанного объекта, а не перечитывается после публикации. `202` — только после записи оригинала в `staging/` и `COMMIT` вложения, задания и outbox.
- Состояния: `queued → processing → ready | failed`; `processing → queued` при временной ошибке или истёкшей аренде; `failed → queued` только явным replay. `ready` не откатывается. `ready` выставляется, только когда записаны оригинал и все обещанные уровнем варианты.
- `/content` для `queued`, `processing`, `failed` — `409 conflict` для любого `variant`, включая `original`; неизвестный `variant` — `400`; отсутствующий вариант `ready`-вложения — `404`; посторонний — `404`. Варианты: `thumbnail` JPEG вписан в 256×256 без увеличения, EXIF orientation применяется, alpha на белом, размеры вниз, минимум 1 px.
- Сообщение: вложение `queued`/`processing` прикрепляется (`201`), `failed` — `409`, вложение другого чата или неизвестное — `404`.
- Сообщение брокера — ровно поля `jobs.schema.json`; `job_id` не меняется при redelivery, `attempt` растёт только при управляемом повторе через outbox. Ключ эффекта — `(attachment_id, pipeline_version, variant)`.
- Сохраняются правила lab4 (сырые байты, тип по содержимому, скачивание только через API без redirect), lab3 (`X-Instance-Id`, `Idempotency-Key`, LB не повторяет upload), lab2 (`Basic` только на входе, `Bearer` дальше, `WWW-Authenticate` по пути) и lab1 (формат ошибки, посторонний → `404`, keyset `(created_at, id)`, время RFC 3339 с `Z`).
- Upload: `POST /api/v1/chats/{chat_id}/attachments?filename=…`, тело — сырые байты (не multipart), `Content-Type: image/png|image/jpeg`. Сначала `401`, затем объявленный `Content-Length` (`413`). Дедлайн запроса продлевается переданными байтами тела по `MIN_TRANSFER_RATE_BYTES` (128 KiB/s): медленный, но идущий upload и скачивание не обрываются. `>10485760` байт или `>40 000 000` пикселей — `413`; тип по содержимому не совпал, битый файл, иной `Content-Type` — `415`; `filename` пустой, пробельный, длиннее 255 code points или с `/`, `\`, NUL, управляющими символами — `400`. Object key назначает сервер. `201 Attachment` (`status=ready`, `variants=[]`, `error_code=null`, lowercase `sha256`, `size_bytes` оригинала) — только после записи в S3 и `COMMIT` метаданных. Кода `409` у upload нет.
- `GET /api/v1/attachments/{id}` и `/content?variant=original` — только участникам чата вложения, посторонний и неизвестный id — `404`. Скачивание отдаёт исходные байты с истинным `Content-Type`, без redirect, с `X-Request-Id` и `X-Instance-Id`.
- `Message.attachment_ids` обязателен в каждом ответе (`[]` у текстовых, в том числе в replay и истории). `CreateMessage.attachment_ids` — 0–10 уникальных UUID (иначе `400`), только вложения этого чата (иначе `404`); `text=""` допустим только с вложением. Отсутствующий `attachment_ids` и `[]` — одно тело для `Idempotency-Key`.
- Сохраняются правила lab3 (`X-Instance-Id`, `Idempotency-Key`, LB не повторяет `POST /users`, `/chats`, upload), lab2 (`Basic` только на входе, `Bearer` дальше, `WWW-Authenticate` по пути, logout `204`, TTL) и lab1 (формат ошибки, посторонний → `404`, keyset `(created_at, id)`, время RFC 3339 с `Z`).
## Правила работы с репозиторием
- Поздние исправления ЛР3 перенесены из immutable snapshot `ba78cf6da439a4ec60fd59389583b38285b0b2b1`; диапазон от `f591fa64e525679a31c9db7f942d36c789e1a12f` и применимость evidence описаны в `evidence/forward-port.md`.
- Только свой Compose project `mtusi2026lab4` либо `hlpipe-lab4-*` под разрешённым working_dir; HTTP 18084, остальные host-порты 24000–24999. `NO_PROXY` и `no_proxy`: localhost,127.0.0.1,::1. Чужие контейнеры не останавливать, WIP и volumes сохранять. Совместный Docker допустим; эксклюзивность только в финальном release.
- Runner назначает одного агента переноса и реализации 3→4→5 с evidence, затем review → отдельный fix при major → re-review, отдельный report и одного агента нагрузки/публикации. Грейды одной лабы последовательны; review/report предыдущей могут идти параллельно реализации следующей. Самостоятельных агентов, push и Telegram нет; runner/state не менять. Публикация только в назначенной фазе PUBLICATION в private MTUCI-Labs.
- Исправлять критичное: major — доказанная угроза безопасности, данным, доступности или неработающий обязательный сценарий. Прочие minor остаются в findings и ограничениях REPORT и не блокируют этап. Пригодные измерения сохраняются; повторяется только затронутая или признанная непригодной серия с указанной причиной и фоном нагрузки.
- Не менять и не ослаблять `contracts/`, `tests/`, `README.md`, `COURSE.md`, рубрику. Расхождение оформляется вопросом преподавателю.
- Код — `src/messenger/`, миграции — `src/messenger/migrations/NNNN_*.sql`, конфигурация LB, нагрузки, S3 и брокера — `infra/`, хуки и обвязка стенда — `scripts/`, собственные тесты — `student-tests/`, обезличенные доказательства — `evidence/`.
- Код — `src/messenger/`, миграции — `alembic/versions/NNNN_*.py`, конфигурация LB, нагрузки и S3 — `infra/`, хуки и обвязка стенда — `scripts/`, собственные тесты — `student-tests/`, обезличенные доказательства — `evidence/`.
- PostgreSQL — SQLAlchemy 2 async с asyncpg как драйвером; ORM-модели внутри зон, Alembic принимает legacy-схему только после сверки журнала и каталога.
- Без комментариев в коде; отступы — пробелы (`[tool.ruff.format]`); Python 3.14 без `from __future__ import annotations` и `TYPE_CHECKING`.
- Порты реплик API, S3, AMQP наружу не публикуются: только LB и UI брокера на `127.0.0.1`. API к брокеру не подключается. Клиенты брокера не объявляют очереди: топология — в `infra/rabbitmq/definitions.json`, права configure есть только у оператора.
- Порты реплик API и S3 наружу не публикуются: только LB. Нет `container_name`, `hostname` и общего `INSTANCE_ID` у сервиса `api`. Root-ключи S3 есть только у `s3`, `s3-init` и `s3-cli`; API получает отдельный ключ только на объекты bucket (`Get/Put/DeleteObject`), сверка — свой ключ (`ListBucket`, `Get/DeleteObject`). `s3-init` и `s3-cli` работают от uid 65534, `migrate` и `reconciler` — с `init: true`.
- `REPORT.md`: команды из чистого clone, архитектура, таблица «критерий → команда → наблюдение → файл», таблица отказов. PASS без команды не доказательство; для отказов — какой контейнер реально остановлен (`docker ps -a`).
- Ветка `solution/bpi2303-kostylev`, коммиты на английском, перед каждым — `make lint`. Никогда не коммитить `.env`, `secrets/`, токены, ключи S3, пароли брокера, volumes, дампы.
- Отчётный этап меняет только `REPORT.md`, `AGENTS.md` и `evidence/**/*.md`; код, конфиги, OpenSpec и сырые измерения не меняет. Docker и нагрузку не запускает. `make student-test` поднимает зависимости: сохранённый результат или collection не выдаётся за новый полный прогон.
- Ветка `solution/bpi2303-kostylev`, коммиты на английском, перед каждым — `make lint`. Никогда не коммитить `.env`, `secrets/`, токены, ключи S3, volumes, дампы.
## Уровни оценки
Решение заявлено на **«5»** с треком 2 «Доказанная идемпотентность pipeline»; таблица доказательств — в `REPORT.md`.
Цель — **«5»**, трек 2 «Согласованность двух хранилищ (reconciler)». На snapshot `7a0ebac2aa9e1d8602054ca4c7c1b0c23d3bfad4` ревью прошло без открытых major. Финальная validation на `5e49502ae78fa48b992c97418e490666c699726d` с идентичным runtime закрыла динамический долг обоих PNG-фиксов: `evidence/load-validation.md`. Сохранён minor Unicode-surrogate → HTTP 500 (`src/messenger/messaging/entrypoints/schemas.py:35`, `evidence/forward-final-2026-11-06/known-minor-http.txt`).
- **3** — `202 queued` после staging и `COMMIT` задания с outbox; отдельные `broker`, `relay`, `worker` в стенде; durable quorum queue, publisher confirm, ручной `ack` после `COMMIT`; состояния `queued/processing/ready/failed`, оригинал в `originals/` и thumbnail; ограниченный retry (`JOB_MAX_ATTEMPTS=5`) и `failed` с `error_code`; повтор job без второго набора вариантов; worker остановлен → upload → сообщение → рестарт API и broker → worker → `ready`; минимум lab4 сохранён.
- **4** — crop и optimized WebP, лимиты worker по байтам, пикселям, времени и памяти, crash между `COMMIT` и publish, backoff с jitter и классификация ошибок, DLQ и replay, crash после записи объекта до `ack`, lease и fencing для зависшего `processing`, prefetch, очистка staging.
- **5** — трек 2: `pipeline_version` 1 и 2, монотонная публикация, автоматический fault-injection (дубль, reorder, crash до и после side effect, устаревшая job) и проверка инвариантов одной командой.
Таблица критериев — в `REPORT.md`, команды и SHA — в `evidence/README.md`. Новая серия использует отдельный разрешённый project со свежими volumes; `reset-data`, `down -v`, reset/clean и удаление пользовательских данных запрещены. После Docker-этапа остановить только свои стенды, сохранив volumes. При изменениях проверять применимость по diff: повторять лишь затронутые/непригодные серии с причиной и фоном. Документационный коммит измерений не обесценивает.
Исторические upload-memory и конкурентные upload до PNG-фиксов не доказывают RAM/производительность нового инспектора. Финальная validation выполнена: 721 собственная проверка (719 + адресный повтор 2 setup errors RustFS), 7 stack, PNG/JPEG через LB/RustFS; матрица 3 слота × 1/10 MiB × 10/20/40 клиентов ×3: 840/840×201, API ≤440 MiB, OOM 0; 10 PNG 40 MP RGBA16: 10×201, API ≤270,828 MiB; upload при сверке: 3341×201, 67 проходов, lost_ready=0. Сырьё — `evidence/png-final-2026-11-06/`. Эти пригодные серии повторять без нового изменения/обоснованной непригодности запрещено. Контроль 64/3 оставлен историческим. 27 пригодных cost-замеров reconciler на `3402fd69d4922e500035a204d957be2cccaeb85a` сохраняются: измеряемый путь не менялся. Отрицательный вывод о линейности времени и разброс deep 100k не скрываются.
- **3** — RustFS и приватный bucket в общем стенде, метаданные в PostgreSQL; upload `201 ready` после записи и `COMMIT`, побайтное скачивание вторым участником, `404` постороннему, `403` анонимному GET в S3; лимиты 10 MiB / 40 MP, тип по содержимому, опасные `filename`; upload → стоп обслужившей реплики → download через другую; restart с volumes; недоступный S3 → `503` при работающих текстах; минимум lab3 сохранён.
- **4** — негативные тесты файлов без `500`; компенсация сбоя между S3 и БД под блокировкой строки и фоновая уборка намерений `pending` старше `UPLOAD_GRACE_SECONDS` (`SKIP LOCKED`, объект раньше строки); слоты загрузки на воркер, ограниченные буферы сокетов LB и API, фиксированный порог `mmap` glibc и замер ≥10 одновременных загрузок; идемпотентный bootstrap, ограниченные ключи API, закрытая консоль, проверка приватности вне API.
- **5** — трек 2: one-off `reconciler` (`python -m messenger.attachments.entrypoints.reconcile`, по умолчанию `--dry-run`) сливает отсортированный листинг bucket и keyset-страницы `attachments` по `object_key` (O(N) сравнений, O(страница) памяти; линейность времени в замерах не подтвердилась); объект без строки старше grace + skew удаляется после повторной проверки строки, готовые строки без объекта или с другими байтами уходят в карантин (миграция `0004`, `/content` → `404`) и не удаляются, `pending` старше grace удаляется (объект, затем строка), карантин снимается только после совпавшего SHA-256 объекта (и без `--deep`); удаление намерения — `audit.attachment_discarded reason=reconcile`; SQL-страниц `⌈N/страница⌉`; один проход за раз (`pg_try_advisory_lock`); повторный `--apply` — 0 действий; стоимость обхода 1k/10k/30k/100k объектов с закреплёнными CPU и отбраковкой прогонов с чужой нагрузкой (`evidence/reconcile/`).
+1 -1
View File
@@ -1,4 +1,4 @@
# Памятка преподавателю — лабораторная 5
# Памятка преподавателю — лабораторная 4
## Что подготовлено
+7 -83
View File
@@ -11,25 +11,18 @@ RATE ?= 100
FROM_REV ?=
SHIFT ?= 0
SCRIPTS_PY = scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py \
scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py \
scripts/make_images.py scripts/pipeline_suite.py scripts/pipeline_evidence.py
scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
SCENARIO ?= failover-upload
PSQL = $(COMPOSE) exec -T postgres psql -U messenger -d messenger -X -q
TRACK2_OUTPUT ?= evidence/track2.json
TRACK2_SCENARIOS = smoke_pipeline,duplicate_after_ready,crash_commit_publish,crash_publish_confirm,crash_after_s3_before_commit,crash_after_commit_before_ack,lease_expiry_fencing,crash_before_side_effect,worker_kill_mid_task,duplicate_in_flight,reorder_attempts,reorder_versions,stale_after_new_version
PIPELINE_VERSION ?= 2
PYTEST_ARGS ?=
.PHONY: help check validate test load test-persistence test-failover \
install lint format typecheck student-test \
secrets up down reset-data migrate ps logs restore lb-check failover-evidence stack-evidence \
persistence-evidence storage-evidence cache-evidence test-faults seed explain \
limits detection failover-each rolling-update lab4-level4 \
persistence-evidence storage-evidence cache-evidence test-faults faults-evidence seed explain retry-check \
limits detection failover-each rolling-update level4 \
scenario s3-check attachments-evidence upload-faults upload-memory \
images queues topology worker-stop worker-start broker-restart suite-preflight level3 \
pipeline-evidence level4 replay failed dlq \
faults-evidence retry-check reconcile reconcile-demo reconcile-cost load-evidence \
clean-clone-evidence overload-leftovers
reconcile reconcile-demo reconcile-cost load-evidence clean-clone-evidence overload-leftovers
.NOTPARALLEL:
@@ -38,14 +31,8 @@ help:
@echo "install/lint/typecheck/student-test: студенческий тулчейн"
@echo "secrets/up/down/migrate/ps/logs: стенд Docker Compose; reset-data: намеренное удаление volumes"
@echo "restore: вернуть остановленные реплики; lb-check: реплики на одном токене и 20 гонок одного ключа"
@echo "lab4-level4 = limits, lb-check, detection, failover-each, rolling-update [FROM_REV=<коммит>]; RATE=$(RATE) rps"
@echo "scenario SCENARIO=failover-upload|s3-outage → evidence/<сценарий>.json; s3-check; attachments-evidence"
@echo "upload-faults: негативный suite, компенсация, уборка, обрыв и зависание загрузки против стенда"
@echo "upload-memory: пик памяти реплик при 10/20/40 одновременных загрузках 1 и 10 MiB → evidence/upload-memory/"
@echo "lab5: queues, topology, worker-stop/worker-start, broker-restart, images, suite-preflight, level3, level4"
@echo "lab5 оператор: failed (реестр), replay ID=<attachment_id>, dlq (просмотр DLQ без извлечения)"
@echo "retry-check: потерянный ответ на живой и на убитой реплике, повтор тем же ключом"
@echo "lab4-level4 = limits, lb-check, detection, failover-each, rolling-update [FROM_REV=<коммит>]; RATE=$(RATE) rps"
@echo "level4 = limits, lb-check, detection, failover-each, rolling-update [FROM_REV=<коммит>]; RATE=$(RATE) rps"
@echo "scenario SCENARIO=failover-upload|s3-outage → evidence/<сценарий>.json; s3-check; attachments-evidence"
@echo "upload-faults: негативный suite, компенсация, уборка, обрыв и зависание загрузки против стенда"
@echo "upload-memory ARGS='--out evidence/upload-memory/runN': пик памяти реплик при 10/20/40 загрузках 1 и 10 MiB"
@@ -98,11 +85,9 @@ student-test:
secrets:
sh scripts/secrets.sh
sh scripts/broker-secrets.sh
up: secrets
$(COMPOSE) build
$(COMPOSE) up -d --wait
$(COMPOSE) up -d --build --wait
scripts/lb-wait.sh
down:
@@ -151,7 +136,7 @@ endif
--out evidence/rolling$(if $(FROM_REV),-from-$(FROM_REV)) \
-- scripts/rolling-update.sh
lab4-level4: limits lb-check detection failover-each rolling-update
level4: limits lb-check detection failover-each rolling-update
scenario:
$(PYTHON) scripts/lab4_scenarios.py $(SCENARIO) --base-url "$(BASE_URL)" --restore --output evidence/$(SCENARIO).json
@@ -224,64 +209,3 @@ explain: seed
echo "\$$ make explain # scripts/sql/explain-history.sql"; \
$(PSQL) -f - < scripts/sql/explain-history.sql; } > evidence/explain-history.txt
cat evidence/explain-history.txt
images:
$(PYTHON) scripts/make_images.py
queues:
sh scripts/broker.sh queues
topology:
{ echo "date: $$(date -u +%FT%TZ) commit: $$(git rev-parse --short HEAD)"; \
echo "$$ rabbitmqctl list_queues -p messenger name type durable policy messages"; \
$(COMPOSE) exec -T broker rabbitmqctl -q list_queues -p messenger name type durable policy messages; \
echo "$$ rabbitmqctl list_consumers -p messenger"; \
$(COMPOSE) exec -T broker rabbitmqctl -q list_consumers -p messenger queue_name ack_required prefetch_count; \
echo "$$ rabbitmqctl list_permissions -p messenger"; \
$(COMPOSE) exec -T broker rabbitmqctl -q list_permissions -p messenger; \
echo "$$ rabbitmqctl list_users"; \
$(COMPOSE) exec -T broker rabbitmqctl -q list_users; \
echo "$$ docker compose ps"; \
$(COMPOSE) ps --format '{{.Service}}\t{{.Status}}\t{{.Ports}}'; } > evidence/topology.txt
cat evidence/topology.txt
worker-stop:
sh scripts/worker.sh stop
worker-start:
sh scripts/worker.sh start
broker-restart:
sh scripts/broker.sh restart
suite-preflight:
BASE_URL="$(BASE_URL)" $(PYTHON) scripts/pipeline_suite.py --preflight
level3:
BASE_URL="$(BASE_URL)" $(PYTHON) scripts/pipeline_suite.py --level 3 --output evidence/level3.json
level4:
BASE_URL="$(BASE_URL)" $(PYTHON) scripts/pipeline_suite.py --level 4 --output evidence/level4.json
failed:
$(COMPOSE) run --rm --no-deps -T worker python -m messenger.admin failed
replay:
@test -n "$(ID)" || (echo "Set ID=<attachment_id>"; exit 2)
$(COMPOSE) run --rm --no-deps -T worker python -m messenger.admin replay --attachment-id "$(ID)"
dlq:
sh scripts/broker.sh dlq
pipeline-evidence:
$(PYTHON) scripts/pipeline_evidence.py --base-url "$(BASE_URL)" > evidence/pipeline-stand.txt; \
status=$$?; cat evidence/pipeline-stand.txt; exit $$status
.PHONY: track2 reprocess
track2:
BASE_URL="$(BASE_URL)" $(PYTHON) scripts/pipeline_suite.py --level 5 --only "$(TRACK2_SCENARIOS)" --output "$(TRACK2_OUTPUT)"
reprocess:
@test -n "$(ID)" || (echo "Set ID=<attachment_id>"; exit 2)
$(COMPOSE) run --rm --no-deps -T worker python -m messenger.admin reprocess --attachment-id "$(ID)" --pipeline-version "$(PIPELINE_VERSION)"
+33 -33
View File
@@ -1,6 +1,6 @@
# Лабораторная 5. Очереди и асинхронная обработка изображений
# Лабораторная 4. S3-хранилище и вложения
Отделить приём файла от тяжёлой обработки, корректно переживать повторную доставку и остановку worker.
Разделить метаданные и бинарное содержимое, добавить изображения в сообщения и сохранить доступ к ним при переключении API-реплики.
Это **skeleton**, а не готовый сервер. Здесь есть задание, контракт и публичные проверки. Реализацию приложения, Dockerfile и требуемую инфраструктуру пишет студент. Язык и framework свободные; UI не обязателен.
@@ -8,42 +8,41 @@
## Откуда начинаем
Нужен минимум lab4. POST upload теперь возвращает 202 queued, а готовность выясняется через метаданные. В HTTP upload клиент по-прежнему передаёт все байты.
Перенесите минимум lab3. Дополняются поля сообщения и endpoint вложений; прежние текстовые POST остаются валидными.
**Архитектура:** API → устойчивый staging + запись задания → брокер → worker → конечный S3 + PostgreSQL. Клиент опрашивает статус.
**Архитектура:** Клиент → LB → API × 2+ → PostgreSQL (метаданные) + приватное S3-хранилище (байты).
## Что сделать
1. Выберите RabbitMQ, Redis/Valkey Streams, NATS JetStream или другой брокер с persistence и подтверждениями. Обычный Pub/Sub без хранения не подходит.
2. Разделите приём, durable staging, публикацию задания, обработку и фиксацию результата. Прочитайте contracts/attachment-states.md.
3. Реализуйте worker отдельно от API: публикация оригинала в конечный S3-prefix и thumbnail 256×256 по правилам контракта.
4. Добавьте конечные состояния, ограниченные повторы и идемпотентную запись результатов. Не помещайте bytes или credentials в сообщения брокера.
5. Остановите worker, загрузите файл, перезапустите API/worker, убедитесь в завершении принятой задачи. Затем проверьте повторную доставку.
1. Выберите один S3-совместимый сервер: MinIO, SeaweedFS или RustFS. Закрепите проверенную версию образа и опишите создание приватного bucket.
2. Спроектируйте Attachment и связь с чатом/сообщением. S3 object key назначает сервер, filename используется только для отображения.
3. Реализуйте синхронный binary upload PNG/JPEG с ограничениями, сохранение метаданных и авторизованный download через API.
4. Включите S3 и persistent volumes в общий Compose/Swarm. Проверьте, что другая API-реплика скачивает файл после остановки загрузившей.
5. Проверьте недоступность S3, чужой чат и restart всего стенда.
## Оценка «3»: работающий минимум
- Весь минимум lab4 сохранён с переходом upload 201 → 202. API возвращает 202 только после устойчивого приёма оригинала и сохранения задания; остановка API после ответа не теряет работу.
- В общем Compose/Swarm есть отдельные broker и worker. Сообщения durable, доставка at least once, подтверждение только после устойчивого эффекта. Недоступность worker не заставляет API выполнять resize синхронно.
- Состояния queued/processing/ready/failed доступны в API. Worker сохраняет оригинал и один thumbnail; original неизменен, thumbnail соответствует контракту. Публичный smoke проходит.
- Есть ограниченный retry (конкретное число попыток в конфигурации, например 5), финальное failed с безопасным error_code. Повтор одной job не создаёт второго набора вариантов.
- Демонстрация: worker остановлен → upload 202 → сообщение с вложением создано → API перезапущен → worker запущен → ready и доступный thumbnail. Принятое задание не исчезает при рестарте broker с volume.
- Все обязательные возможности lab3 сохранены. S3-сервер находится в общем стенде; метаданные вложений живут в PostgreSQL, байты — в приватном bucket, не в БД или локальном каталоге API.
- POST вложения возвращает 201 ready после сохранения; оригинал скачивается побайтно. Message с attachment_ids читается участниками чата. Публичный smoke проверяет checksum и отсутствие доступа у постороннего.
- Принимаются реальные PNG/JPEG ≤10 MiB и ≤40 млн пикселей; MIME проверяется по содержимому, опасные filename отклоняются, лимиты применяются до неограниченного чтения/декодирования.
- Upload → остановка обслужившей API-реплики → download через другую возвращает тот же файл. Restart с сохранением volumes сохраняет метаданные и оригинал.
## Оценка «4»: уровень стажёра/джуна
Весь уровень 3 **и все** пункты ниже:
- Добавлены crop 128×128 и optimized WebP по контракту, параметры качества/удаления метаданных описаны. Невалидные/огромные изображения ограничены по bytes, пикселям, времени и памяти worker.
- Разрыв между PostgreSQL и broker закрыт transactional outbox или другой доказанной схемой восстановления намерения. Внедрён crash между COMMIT и publish; после восстановления задача доходит до ready без ручного создания нового задания.
- Retry использует backoff с jitter, различает постоянные/временные ошибки; есть DLQ/реестр failed и безопасный явный replay. «Повторить» не означает безусловно исполнить дубль уже успешной job.
- Проверена остановка worker после записи объекта, но до ack; повтор завершает тот же результат. Есть timeout/lease для зависшего processing, ограниченная конкуренция/prefetch и очистка staging после безопасной фиксации.
- Тесты покрывают слишком большой файл, повреждённое изображение, подмену MIME, чужое attachment_id и привязку файла другого чата. Пользовательская ошибка не превращается в 500.
- Прерывание загрузки и отказ между записью S3/БД не оставляют вечных неучтённых объектов: есть документированный механизм компенсации/сверки/очистки с безопасным grace period.
- Лимиты/таймауты и потоковая обработка не позволяют одной загрузке занять неограниченную RAM. Проведён эксперимент ≥10 одновременных загрузок с измерением пика памяти.
- Bucket bootstrap идемпотентен; API использует отдельные S3 credentials с ограниченными правами. Административная консоль не открыта в общей сети. Есть проверка private bucket вне API.
## Оценка «5»: исследование и доказанный результат
Весь уровень 4 **и один законченный трек на выбор**. Приведите гипотезу, повторяемую методику, результаты и ограничения.
**Трек 1. Очередь под перегрузкой.** Сравните ≥3 настройки concurrency/prefetch на разных размерах изображений. Измерьте throughput, queue lag, p95 времени до ready и RSS; покажите backpressure и ограничение количества принятой работы. Докажите восстановление после перегрузки, объясните компромисс latency/ресурсы.
**Трек 1. Прямой upload.** Добавьте отдельный безопасный presigned-upload flow: короткая подпись, уникальный ключ, проверка принадлежности, размера/checksum при complete, обработка незавершённой загрузки. Сохраните обязательный proxy endpoint. Сравните трафик и RAM API при ≥2 размерах файлов, покажите негативные сценарии.
**Трек 2. Доказанная идемпотентность pipeline.** Постройте versioned pipeline и автоматический fault-injection для дубля, reorder, crash до/после side effect и устаревшей job после новой версии. Зафиксируйте инварианты, покажите отсутствие потери подтверждённых задач и перезаписи нового результата старым. Обсудите почему это не exactly-once доставка.
**Трек 2. Согласованность двух хранилищ.** Разработайте повторяемый reconciler для orphan/missing объектов и метаданных. Внедрите ошибки на обеих сторонах, покажите обнаружение и безопасное исправление с dry-run/повторным запуском. Докажите, что свежие и используемые вложения не удаляются; измерьте стоимость обхода.
## Как начать и проверить
@@ -79,27 +78,28 @@ Smoke не выставляет оценку автоматически. Про
## Сценарий защиты
1. Запустить make test: API возвращает 202, GET доходит до ready, оригинал и настоящий JPEG thumbnail проверяются.
2. Остановить worker своим скриптом, загрузить файл, убедиться, что content отвечает 409, а другие сообщения продолжают работать.
3. Перезапустить API/broker с сохранением volumes, запустить worker; та же запись должна стать ready. Зафиксировать порядок действий и ID без токенов.
4. Для 4: воспроизвести crash после side effect до ack, разрыв COMMIT/publish и replay failed; для 5 — выбранный эксперимент.
1. Загрузить fixture, отправить message с attachment_ids, скачать как второй участник и сравнить SHA-256.
2. С третьим пользователем получить 404 для метаданных и bytes; direct unauthenticated S3 GET не отдаёт объект.
3. Выполнить persistence и failover: общий тест начиная с lab4 сохраняет и повторно читает оригинал через API.
4. Показать, что на API нет обязательного локального файла оригинала. Для 4/5 — отказы и эксперименты.
## Что должно быть в PR
Worker, брокер в общем стенде, схема jobs, migrations/outbox по уровню, конфигурация retry, тесты сбоев и отчёт.
Дополненный стенд, настройка bucket/политики, миграции Attachment, тесты файлов, описание согласованности БД/S3 и результаты.
Заполните `REPORT.md` и [шаблон PR](.github/pull_request_template.md), укажите целевую оценку/трек. Не меняйте обязательный контракт и публичные tests ради зелёного результата. Сохраняйте возможности предыдущих лабораторных в пределах [объявленных переходов](COURSE.md).
## Вопросы на защите
- Чем publisher confirm отличается от consumer ack?
- Что именно уже сохранено в момент 202?
- Почему повторная доставка нормальна и где находится ключ идемпотентности job?
- Как отличить зависший worker от долго работающего и не запустить два неконтролируемых дубля?
- Почему файл в Docker volume одной API-реплики не равен объектному хранилищу?
- Когда можно честно вернуть 201?
- Что произойдёт, если S3 PUT прошёл, а COMMIT в PostgreSQL — нет?
- Почему случайный object key и приватный bucket не заменяют ACL приложения?
## Первичные материалы
- [RabbitMQ reliability](https://www.rabbitmq.com/docs/reliability)
- [Publisher confirms and acknowledgements](https://www.rabbitmq.com/docs/confirms)
- [Redis Streams](https://redis.io/docs/latest/develop/data-types/streams/)
- [NATS JetStream](https://docs.nats.io/nats-concepts/jetstream)
- [S3 object uploads](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)
- [Presigned URLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html)
- [MinIO](https://github.com/minio/minio)
- [SeaweedFS](https://github.com/seaweedfs/seaweedfs)
- [RustFS](https://docs.rustfs.com/)
+409 -349
View File
@@ -1,390 +1,450 @@
# Отчёт — лабораторная 5
# Отчёт — лабораторная 4 «S3-хранилище и вложения»
- Автор, группа: Костылев Артём, БПИ2303
- Целевая оценка: **5**; трек «5» — **трек 2 «Доказанная идемпотентность pipeline»**
- Commit/PR: ветка `solution/bpi2303-kostylev`, PR в репозиторий преподавателя
- Использованные источники, библиотеки и помощь ИИ: FastAPI, gunicorn + uvicorn-worker, dishka и
dishka-faststream, pydantic, structlog, asyncpg, argon2-cffi, redis-py, aiobotocore/botocore, Pillow,
FastStream 0.7 (`faststream[rabbit]`) поверх aio-pika, pytest, ruff, ty (версии — `evidence/environment.txt` и
`uv.lock`); RabbitMQ docs (Reliability Guide, Consumer Acknowledgements and Publisher Confirms, Quorum Queues,
Dead Lettering, Access Control, Definitions), документация FastStream 0.7 через context7 (ack policy, `Channel`,
`RabbitQueue(declare=False)`, publisher confirms), Pillow (`ImageOps.exif_transpose`, режимы и альфа-канал),
Docker Compose (secrets, `depends_on`, healthcheck). Заготовки брокера, compose-фрагмент, хуки и suite
сценариев — из моей подготовки `.prep/lab5`. Решение перенесено из моей лабы 4 и выполнено с помощью Claude
Code; код, стенд и отказы проверены прогонами, перечисленными ниже.
Автор: **Костылев Артём, БПИ2303**. Ветка: `solution/bpi2303-kostylev`.
Цель — **«5», трек 2 «Согласованность двух хранилищ (reconciler)»**.
Финальная validation завершена 2026-11-06 на
`5e49502ae78fa48b992c97418e490666c699726d`: runtime совпадает с прошедшим независимое
ревью `7a0ebac2aa9e1d8602054ca4c7c1b0c23d3bfad4`. Динамический долг обоих PNG-фиксов
закрыт, открытых major не выявлено; известный minor сохранён в ограничениях.
**Заявлена «5», трек 2**, с отрицательным результатом гипотезы о линейном времени.
[Аудит применимости](evidence/load-validation.md) объясняет, какие старые серии приняты
без повторения и какие проверки выполнены заново. Публикация ещё не разрешена.
## Происхождение и применимость доказательств
| Состояние кода | SHA | Что подтверждено и что сохраняется |
| --- | --- | --- |
| Перенос основы ЛР3 на SQLAlchemy/Alembic | `8e4532f6f5c05d902b6e2c310f54320d95585904`, источник `f591fa64e525679a31c9db7f942d36c789e1a12f` | Полная серия уровней 3/4; историческая относительно поздних исправлений |
| Стоимость reconciler | `3402fd69d4922e500035a204d957be2cccaeb85a` | 27 пригодных замеров: измеряемый обход, SQL/S3-адаптеры, зависимости и стенд не менялись; сохраняются с исходным SHA |
| Поздние исправления ЛР3 | `75b93bbba5f29575d3fca1d013cc7e0770d88082`, источник `ba78cf6da439a4ec60fd59389583b38285b0b2b1` | Сессии, NUL/Basic, JSON ошибок LB; 492 теста, 19 stack-тестов, отказы и новые серии. Все 214 путей диапазона учтены в [манифесте переноса](evidence/forward-port.md) |
| Декодируемость PNG | `9387c3d82ab77ea376eecce19a36a22803d35efb` | Битый IDAT с корректными CRC отклоняется; [offline-доказательства](evidence/png-validation-fix/NOTES.md) |
| Единый IHDR | `7c8a1a64899dc0a1b5fa0949c0992ef40722eacf`, архив/ревью `7a0ebac2aa9e1d8602054ca4c7c1b0c23d3bfad4` | Повторный IHDR отклоняется; 407 offline-тестов. [Манифест](evidence/png-header-fix/manifest.json) совпадает с текущими семью файлами |
После `75b93bb…` в runtime изменились только `images.py` и новый `png.py` зоны attachments.
Поэтому старые upload-memory и загрузки во время сверки **не доказывают** память и скорость
нового инспектора. Результаты текстового пути, скачивания, persistence/failover, IAM/bootstrap
сохраняются для неизменённых механизмов; это не повторные прогоны на текущем HEAD.
Серия asyncpg 29–30 октября вынесена из основных таблиц в
[исторический индекс](evidence/README.md#историческая-реализация-asyncpg).
[Индекс evidence](evidence/README.md) связывает команды, SHA и файлы.
[Аудит отчётного этапа](evidence/report-audit-2026-11-06.md) содержит проверки исходных чисел,
ссылок и границ изменений. Сырые результаты не редактировались.
## Запуск из чистого clone
Требуются Docker с Compose v2, `make`, системный Python 3.9+ (публичные проверки и сценарии) и `uv` (собственные
тесты). Образы сторонних сервисов закреплены версией и digest, приложение собирается из исходников.
Нужны Git, Docker Compose v2, make, uv и Python 3.14 для приложения/собственных тестов;
публичным проверкам достаточно системного Python 3.9+. Из основного репозитория можно
создать свежий clone под разрешённым каталогом `.verification/`:
```sh
git clone <repo> && cd mtusi2026lab5 && git checkout solution/bpi2303-kostylev
make secrets # secrets/*: PostgreSQL, Valkey, ключ курсора, root/API/worker-ключи S3, пароли и URL брокера,
# rabbitmq_users.json с хешами паролей; .env из .env.example (существующее не перезаписывает)
git clone --no-hardlinks --branch solution/bpi2303-kostylev . .verification/hlpipe-lab4-defense
cd .verification/hlpipe-lab4-defense
export COMPOSE_PROJECT_NAME=hlpipe-lab4-defense
export COMPOSE_FILE=compose.yaml
export LB_HTTP_PORT=18084 LB_STATS_PORT=24845
export BASE_URL=http://127.0.0.1:18084
export NO_PROXY=localhost,127.0.0.1,::1
export no_proxy=localhost,127.0.0.1,::1
make secrets
docker compose --env-file .env config --quiet
make up # build, затем up -d --wait: postgres, valkey, s3, broker → migrate, s3-init → api ×2, relay, worker → lb
make test # публичный smoke через балансировщик, http://localhost:8080
make up
make test
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
make restore # вернуть остановленную реплику и дождаться её в ротации LB
make suite-preflight && make level3 # сценарии уровня «3» и инварианты → evidence/level3.json
make level4 # сценарии уровней «3» и «4» и инварианты → evidence/level4.json (~8 мин)
make failed # реестр failed-заданий (python -m messenger.admin failed)
make replay ID=<attachment_id> # явный replay failed → queued с audit; ready → noop
make dlq # просмотр DLQ без извлечения (rabbitmqadmin, ack_requeue_true)
make pipeline-evidence # worker остановлен: 202, 409, задание в очереди, SIGTERM relay/worker
make topology # очереди, consumer с prefetch, права, пользователи брокера → evidence/topology.txt
make worker-stop / make worker-start / make broker-restart / make queues # ручная демонстрация защиты
make down # безопасная остановка: контейнеры удаляются, volumes pgdata, valkeydata, s3data, broker-data остаются
make reset-data # НАМЕРЕННОЕ удаление учебных данных, включая байты вложений и очередь: docker compose down -v
docker compose ps -a
make restore
make scenario SCENARIO=failover-upload
make restore
make scenario SCENARIO=s3-outage
make s3-check
make reconcile
make migrate
make down
```
`make up` ждёт `healthy` всех долгоживущих сервисов и кода 0 одноразовых `migrate` (миграции под advisory lock)
и `s3-init` (bucket, анонимный доступ `private`, политики и пользователи API и worker, lifecycle). Топологию
брокера (vhost, exchanges, quorum-очереди, привязки, политики) и пользователей узел RabbitMQ импортирует из
`/etc/rabbitmq/definitions.d` на каждой загрузке; повторный `make up`, `restart.sh` и `broker.sh restart` проходят
без изменений состояния. Наружу публикуются только порты `lb` (`LB_HTTP_PORT` 8080, `LB_STATS_PORT` 8404) и UI
брокера (`BROKER_MANAGEMENT_PORT` 15672), все на `127.0.0.1`. На машине, где выполнялась работа, параллельно
работали стенды других лаб, поэтому в локальном `.env` стояли `LB_HTTP_PORT=18085`, `LB_STATS_PORT=25085`,
`BROKER_MANAGEMENT_PORT=25672`, а проверки запускались с `BASE_URL=http://localhost:18085`. Доказательства уровня
«3» впервые сняты на стенде, поднятом после `make reset-data` (пустые volumes), на коммите `fe26938`; доказательства
уровней «3» и «4» в `evidence/` обновлены на коммите `0b85edf` (стенд пересобран `make up`, volumes сохранены).
Имя clone/project должно быть новым; порт 18084 должен быть свободен. Занявший его чужой
стенд не останавливается. `make secrets` создаёт локальные файлы и не перезаписывает
существующие; содержимое секретов выводить не нужно. `make up` ждёт PostgreSQL/Valkey/RustFS,
`alembic upgrade head`, bootstrap bucket и обе API-реплики в ротации LB. Повторный `make migrate`
не меняет актуальную схему. `make down` сохраняет постоянные volumes; `reset-data`, `down -v`
и удаление пользовательских данных в этом процессе не используются.
Собственные проверки и тулчейн:
Сохранённое воспроизведение из свежего clone: **76,866 с, exit 0**, SHA
`cf41f7c64dcf1dea6da0643f5793bd2e5dd1f03e`, проект `hlpipe-lab4-clean-20261105231220`.
Smoke, persistence, failover, upload→stop→download, S3-outage, 31 проверка S3, dry-run и
повторная миграция прошли; после down остались три volumes.
[Полная команда и вывод](evidence/sqlalchemy-2026-11-06/grade4/clean-clone-command.txt).
Это запуск **до позднего переноса и PNG-фиксов**, а не доказательство запуска нынешнего SHA.
Проверки исходников выполняются отдельно:
```sh
make install # uv sync --group dev (Python 3.14 и зависимости из uv.lock)
make lint # ruff check + ruff format --check (src, student-tests, Python-скрипты стенда) + ty check
make student-test # собственные тесты; поднимают одноразовые PostgreSQL, Valkey, RustFS и RabbitMQ тех же образов
make check # офлайн-проверка skeleton
make validate PYTHON=<venv с requirements-dev.txt>/bin/python # полная валидация OpenAPI и jobs.schema.json
make stack-evidence / make persistence-evidence / make failover-evidence # как в лабах 3–4
make install
make check
make validate
make lint
make student-test
openspec validate --all --strict --no-interactive
```
**Версии и стенд:** Python 3.14.7 в образе `python:3.14-slim-trixie@sha256:51dafde8…`,
`rabbitmq:4.1.8-management-alpine@sha256:54ef5ff5…` (RabbitMQ 4.1.8), `rustfs/rustfs:1.0.4@sha256:ed9210d6…`,
`rustfs/rc:v0.1.36@sha256:ab024bfe…`, `haproxy:3.2.26-alpine@sha256:58938405…`,
`postgres:17.11-alpine@sha256:266d3c25…`, `valkey/valkey:8.1.11-alpine@sha256:2602ace2…`; FastStream 0.7.8,
aio-pika 10.2.1, aiormq 7.2.4, dishka-faststream 0.7.0, Pillow 13.0.0; Docker 28.3.2, Compose 2.38.2. Машина —
Apple M4 Max, 16 CPU, 48 ГБ RAM, macOS 15.1; VM Docker Desktop — 16 CPU, 7.65 ГиБ (`evidence/environment.txt`).
`make student-test` использует одноразовые Docker-зависимости. На отчётном этапе выполнены
только check/validate/lint/OpenSpec и чтение сохранённых доказательств; тесты с Docker и
нагрузки не запускались. Сохранённые полные 492 теста относятся к `75b93bb…`, а 407 unit-тестов
после PNG-фиксов — к `7c8a1a6…`; складывать эти числа в число тестов одного прогона нельзя.
## Архитектура и решения
```
┌─ api ×2 (gunicorn) ─ upload: проверка → PUT staging/<id> ──────────────▶ s3: RustFS
клиент ─HTTP─▶ lb (HAProxy) ─────┤ одна транзакция: attachments(queued) + jobs + outbox + job_events ──▶ postgres
127.0.0.1:8080 └─ 202 снимок queued; GET метаданных/контента читает PostgreSQL и S3 (источник истины)
relay ── SELECT outbox … FOR UPDATE SKIP LOCKED ─▶ publish (confirm, mandatory, persistent) ─▶ broker: RabbitMQ
└─ UPDATE published_at; возврат истёкших аренд; staging у ready и у failed после retention quorum attachments.process
worker ◀── FastStream subscriber, prefetch = WORKER_CONCURRENCY, manual ack ───────────────────────┘ DLX → .dlq
└─ claim (lease_token) → продление аренды → GET staging → процесс рендера: thumbnail, crop, optimized
→ CopyObject originals/<id>, PUT variants/<id>/1/… → COMMIT (fencing, ON CONFLICT DO NOTHING,
published_version < v) → ack
admin (python -m messenger.admin, только PostgreSQL) ── failed: реестр; replay: failed → queued + outbox + audit
сеть edge: lb, broker (UI на 127.0.0.1) ─── сеть backend (internal): все сервисы
```text
клиент → HAProxy :18084 → API ×2, по 2 UvicornWorker
├→ PostgreSQL: метаданные, сессии, сообщения
├→ Valkey: кэш сессий
└→ RustFS: байты оригиналов
migrate → PostgreSQL; s3-init → private bucket и IAM
reconciler → PostgreSQL + RustFS, одноразовый сервис
```
**Источник истины.** PostgreSQL — для всего, что знает система о вложении и задании: статус, ключи staging и
оригинала, опубликованная версия, варианты, попытки, аренда, намерение публикации и журнал переходов. S3 — только
для байтов (`staging/<id>`, `originals/<id>`, `variants/<id>/<версия>/<имя>-<sha256[:16]>.jpg`). Брокер —
транспорт и будильник: сообщение несёт только идентификаторы по `jobs.schema.json`, worker берёт ключи хранилища
из БД. Потерянное сообщение восстанавливается из PostgreSQL (outbox, возврат аренды), лишнее гасится захватом
задания.
Python 3.14, FastAPI, gunicorn/uvicorn-worker, dishka, Pydantic v2, structlog,
**SQLAlchemy 2.0.45 async, asyncpg как драйвер, Alembic 1.16.5**, aiobotocore и Pillow 13.0.0.
Версии зависимостей закреплены в [uv.lock](uv.lock), правила форматирования — пробелы в
[pyproject.toml](pyproject.toml). Образы закреплены digest в [compose.yaml](compose.yaml):
HAProxy 3.2.26, PostgreSQL 17.11, Valkey 8.1.11, RustFS 1.0.4, rc 0.1.36.
**Перенесено из лабы 4 без изменения поведения:** зоны `identity`, `messaging`, `attachments`, порты и адаптеры,
UoW, шина событий с журналом аудита, ASGI-конвейер, Basic → Bearer, Argon2id, сессии в PostgreSQL с кэшем в
Valkey, `X-Instance-Id`, `Idempotency-Key`, HAProxy с проверкой готовности, RustFS с приватным bucket, порядок
проверок upload (лимит тела по маршруту, членство, `filename`, `Content-Type`, слоты, поток со счётчиком,
проверка изображения по заголовку), компенсация и уборка намерений `pending` по grace period, хуки, сценарии и
проверки уровня «4» лабы 4. **Изменено:** upload отвечает `202 queued`, оригинал пишется в `staging/`, вместо
`ready` строка-намерение переходит в `queued` вместе с заданием и outbox; метаданные и `/content` показывают
статусы и варианты; `messaging` отказывает `409` на `failed`-вложение; новые процессы `relay` и `worker`, сервис
`broker`, миграция `0004`; `restart.sh` перезапускает ещё брокер, relay и worker; сценарии лабы 4 ждут `ready`.
Зоны `identity`, `messaging`, `attachments` содержат домен, прикладные порты и адаптеры;
`shared` — платформу, `main.py` — сборку. Межзонная проверка членства идёт через порт
`ChatMembership`, не через импорт инфраструктуры соседней зоны. Pydantic остаётся на HTTP-границе,
ORM-модели `DeclarativeBase` — внутри зон. Сессии создаёт `async_sessionmaker`; UoW получает
свою `AsyncSession` на транзакцию и явно делает COMMIT. Незавершённая транзакция откатывается
при закрытии сессии. SQL строится ORM/Core с параметрами; `asyncpg` не используется как
отдельный прикладной слой запросов. Отправка сообщения — Core CTE под блокировкой строки чата:
квитанция `Idempotency-Key`, сообщение и ссылки на вложения фиксируются вместе.
**Процессы и границы зон.** Три долгоживущих процесса из одного образа: `api` (`messenger.main:create_app()`),
`relay` (`python -m messenger.relay`), `worker` (`python -m messenger.worker`), и одноразовая CLI оператора
`python -m messenger.admin`. `relay.py`, `worker.py` и `admin.py` — сборки процессов рядом с `main.py`; они знают
только зону `attachments` и `shared`. Вся логика pipeline — в зоне `attachments`: домен заданий (`Job` и его
сообщение, `Lease`, `Claim`, `RetryPolicy` с jitter, `FailureCode`, `Outcome`, `ReplayResult`, `FailedJob`, `Variant`,
`fit`), обработчики `ProcessJob`, `PublishOutbox`, `RecoverExpiredLeases`, `CleanStaging`, `ReplayAttachment`, порты
`JobPublisher`, `VariantRenderer`, `Faults`, `Jitter`, расширенные `ObjectStorage`, UoW и `AttachmentDirectory`,
адаптеры FastStream (`infrastructure/rabbitmq.py`), Pillow и пула процессов рендера (`infrastructure/images.py`),
PostgreSQL, `FAULT_POINT` и jitter, точки входа FastStream-подписчика, циклов relay и CLI оператора.
Ядро `shared/` не импортирует ни веб-фреймворк, ни FastStream, ни aio-pika; dishka-контейнер worker и relay
собирается из тех же `PlatformProvider` и адаптеров, что у API, через интеграцию `dishka-faststream`. Вопрос
`messaging` «есть ли среди вложений `failed`» — порт `AttachmentStates` зоны `messaging`, адаптер которого над
`AttachmentDirectory` собирает `main.py`. Правила проверяет `student-tests/api/test_bounded_contexts.py`.
Alembic [env.py](alembic/env.py) использует async engine и `run_sync`, advisory lock и
транзакции миграций. Ревизии: `0001` — базовая схема, `0002` — ключи идемпотентности,
`0003` — вложения/связи, `0004` — карантин. Legacy-схема принимается только после сверки
журнала и каталога в [legacy.py](alembic/legacy.py); произвольный stamp вместо миграции не применяется.
При подготовке отчёта через Context7 сверены закреплённые версии:
[SQLAlchemy, сессии](https://github.com/sqlalchemy/sqlalchemy/blob/rel_2_0_45/doc/build/orm/session_basics.rst),
[Alembic, async migrations](https://github.com/sqlalchemy/alembic/blob/rel_1_16_5/docs/build/cookbook.rst).
**Схема** (`0004_jobs.sql`, expand): у `attachments` статусы `pending/queued/processing/ready/failed`,
`staging_key`, `original_key`, `published_version`, `error_code` (CHECK: `invalid_image`, `processing_failed`,
`retry_exhausted`); `object_key` лабы 4 перенесён в новые колонки и оставлен nullable до contract-миграции. Новые
таблицы: `attachment_variants` с PK `(attachment_id, pipeline_version, name)` — ключ эффекта — и уникальным
`object_key`; `jobs` (`UNIQUE (attachment_id, pipeline_version)`, `attempt`, `claims`, `lease_token`,
`lease_until`, `next_attempt_at`, `last_error`); `outbox` (`payload jsonb`, `available_at`, `published_at`);
`job_events` (журнал переходов). Частичные индексы: `outbox_pending_idx (available_at, id) WHERE published_at IS
NULL` — выборка relay, `jobs_lease_idx (lease_until) WHERE status = 'processing'` — истёкшие аренды,
`attachments_staged_idx (updated_at) WHERE staging_key IS NOT NULL` — уборка staging (`ready` и `failed` после
retention). `0005_failed_registry.sql` (expand, только индекс): `jobs_failed_idx (updated_at DESC) WHERE status =
'failed'` — реестр оператора `ORDER BY updated_at DESC LIMIT n`.
**Источники истины.** PostgreSQL хранит владельца/чат, имя, MIME, размер, SHA-256, размеры
изображения, статус, object key и ссылки сообщений. Байты — только в приватном RustFS,
ключ `attachments/<uuid>` назначает сервер. API read-only, без data volumes; `/tmp` — tmpfs.
`attachments.object_key` имеет UNIQUE и `COLLATE "C"`; частичный индекс pending обслуживает
уборку; FK `message_attachments (attachment_id, chat_id)` не даёт привязать чужой чат или
удалить используемое вложение. История использует keyset `(created_at, id)`.
**Upload и что сохранено в момент `202`.** Лимиты и проверки лабы 4 не изменились. После проверки изображения:
`INSERT attachments (pending, staging_key)` и `COMMIT` → `PutObject staging/<id>` → одна транзакция:
`UPDATE attachments SET status='queued' WHERE status='pending'`, `INSERT jobs (pipeline_version=1, attempt=1)`,
`INSERT outbox (payload по jobs.schema.json)`, `INSERT job_events ('enqueued')` → `202`. Ответ — снимок объекта
из памяти (`queued`, `variants=[]`, `error_code=null`), не перечитанный после фиксации. К моменту `202` устойчиво
сохранены полный проверенный оригинал в S3, метаданные, задание и намерение его публикации. API не строит
вариантов и не подключается к брокеру: недоступный worker или брокер не влияет на upload.
**Upload.** Сначала аутентификация (`401`), объявленный размер (`413`), членство (`404`),
filename (`400`), MIME (`415`). Поток ограничен 10 485 760 байтами и считается также без
Content-Length; SHA-256 вычисляется при чтении. Тело собирается в ограниченный буфер под
`UPLOAD_CONCURRENCY=3` на worker; две проверки изображений на worker работают в потоках.
Лимит 40 млн пикселей проверяется до распаковки. PNG требует единственный первый IHDR,
проверку CRC и потоковую проверку zlib/Adler-32, длины строк и фильтров, включая Adam7.
Дополнительные блоки распаковки — по 64 KiB, полного массива пикселей нет. JPEG проверяется
через `draft` 1/8 и `load`. Ошибка изображения → `415` до намерения в БД/S3.
Оба PNG из ревью отклоняются с 415 в ASGI-регрессиях и через настоящий LB/RustFS.
После двух запросов число строк/объектов осталось 7/7; корректные PNG/JPEG скачаны
вторым участником побайтно: [финальная сверка](evidence/png-final-2026-11-06/png-roundtrip.json).
**Outbox и relay.** Раз в `OUTBOX_POLL_SECONDS` (1 с) relay в транзакции берёт до 50 строк `WHERE published_at IS
NULL AND available_at <= now() ORDER BY available_at, id FOR UPDATE SKIP LOCKED`, публикует каждую через
`RabbitBroker.publish` (exchange `attachments` без объявления, routing key `attachment.process.v1`,
`persist=True`, `mandatory=True`, `message_id = job_id`, `type = attachment.process.v1`, тело — ровно `payload`)
и той же транзакцией ставит `published_at`. Канал открыт с `publisher_confirms=True` и `on_return_raises=True`:
unroutable-сообщение, `basic.nack` или обрыв соединения — ошибка, строка остаётся неопубликованной и
повторяется. Publisher confirm — подтверждение брокера, что сообщение записано в quorum queue; обработку он не
подтверждает. Раз в `SWEEP_INTERVAL_SECONDS` (5 с) relay возвращает задания `processing` с истёкшей арендой
(`queued`, `attempt + 1`, новая строка outbox, событие `lease_expired`; на пределе попыток — `failed`) и удаляет
staging-объекты `ready`-вложений (у worker нет права `DeleteObject`).
Порядок публикации: `INSERT pending + COMMIT → PUT → UPDATE ready + COMMIT → 201`.
Метаданные и скачивание доступны только участникам чата; чужой и неизвестный id дают `404`.
Скачивание идёт через API кусками 64 KiB, с исходными байтами и истинным MIME, без redirect.
`attachment_ids` присутствует во всех ответах сообщений, отсутствие и `[]` дают один fingerprint.
**Worker: захват, фиксация, `ack`.** FastStream `RabbitBroker` (`logger=None`: журнал только через порт `Logger`),
подписчик на `RabbitQueue("attachments.process", declare=False, quorum)` без привязки к exchange,
`Channel(prefetch_count=WORKER_CONCURRENCY)`, `AckPolicy.MANUAL`, `graceful_timeout` 5 с. Сообщение не по схеме
(pydantic-модель с `extra="forbid"`) — `reject(requeue=False)` в DLX. Дальше:
**Компенсация.** После отказа фиксации ready новая транзакция блокирует строку `FOR UPDATE`:
ready не трогается; у pending удаляется объект, затем строка. При отмене/неизвестном исходе
PUT намерение остаётся для уборки. Sweeper раз в 30 с выбирает до 100 pending старше 900 с
через `FOR UPDATE SKIP LOCKED`, удаляет объект раньше строки и публикует
`audit.attachment_discarded`. Готовые и используемые вложения не выбираются.
1. *Захват* — `UPDATE jobs SET status='processing', lease_token=<новый uuid>, lease_until=now()+JOB_TIMEOUT_SECONDS,
claims=claims+1 WHERE job_id=$1 AND attachment_id=$2 AND pipeline_version=$3 AND ((status='queued' AND
next_attempt_at наступил) OR (status='processing' AND lease_until < now()))`, вложение `queued → processing`,
событие `claimed`. Нет строки — задание уже `done`/`failed`, держится живой арендой или повтор ещё не наступил:
событие `duplicate_noop` и `ack`. `attempt` из сообщения информационный, захват идёт по `job_id`.
2. *Побочные эффекты под арендой* — сначала продление аренды (`UPDATE jobs SET lease_until = now() + JOB_TIMEOUT_SECONDS
WHERE job_id AND lease_token AND status='processing'`), затем задачей: чтение `staging/<id>`, рендер трёх вариантов
в процессе рендера, `CopyObject staging → originals/<id>`, `PutObject variants/<id>/1/<имя>-<sha256[:16]>.<jpg|webp>`;
пока задача идёт, аренда продлевается раз в `JOB_TIMEOUT_SECONDS / 3`. Продление не удалось (аренду забрали или
задание уже вернули в очередь) — задача отменяется вместе с процессом рендера, событие `fenced`, `ack`. Ключ
содержит хеш: повтор с другими байтами не перезапишет объект, на который уже ссылается БД.
3. *Фиксация* — одна транзакция: `UPDATE jobs SET status='done' … WHERE status='processing' AND lease_token=$2`
(0 строк — аренду перехватили: событие `fenced`, ничего не публикуется); `INSERT attachment_variants … ON
CONFLICT DO NOTHING`; `UPDATE attachments SET status='ready', published_version=$v, original_key … WHERE
published_version < $v` (0 строк — опубликована более новая версия: задание `superseded`); событие `done`.
4. *`ack` — только после `COMMIT`.* Ошибка PostgreSQL до или во время фиксации — `nack(requeue=True)` через 1 с;
если аренда уже взята, задание вернёт relay по её истечении.
**Ресурсы и отказы.** У API 1 CPU/512 MiB на реплику, у LB 1 CPU/128 MiB,
PostgreSQL 2 CPU/1 GiB, RustFS 1 CPU/512 MiB, Valkey 0,5 CPU/128 MiB;
reconciler 1 CPU/256 MiB. Условия cost-эксперимента отличаются и указаны отдельно.
Слоты дополнены буферами HAProxy 64 KiB, максимумом TCP-буфера API 256 KiB и
`MALLOC_MMAP_THRESHOLD_=131072`. S3 connect/read = 1/2 с, две попытки; запрос — 8 с,
LB — 10 с простоя. Дедлайн продлевается переданными байтами при пороге 128 KiB/s,
поэтому идущая передача может длиться дольше 8 с. LB не повторяет upload.
Readiness проверяет PostgreSQL, но не S3: отказ хранилища изображений сохраняет текстовый путь.
**Повторы, jitter и классификация ошибок.** Временная ошибка — `Unavailable` от S3 или PostgreSQL, падение процесса
рендера по внешней причине (`BrokenProcessPool`, например OOM killer), точка `transient_error` — возвращает задание
и вложение в `queued` (не `failed` — smoke падает на первом `failed`) с тем же `job_id`, `attempt + 1` и новой
строкой outbox. Задержка — equal jitter: `d = min(JOB_BACKOFF_CAP_SECONDS=60, JOB_BACKOFF_BASE_SECONDS · 2^(n−1))`,
задержка `d/2 + U(0, d/2)` (`RetryPolicy.delay(attempt, spread)`, `spread` — порт `Jitter`, адаптер на
`secrets.SystemRandom`); `next_attempt_at` и `available_at` считает PostgreSQL (`now() + make_interval`), задержка
пишется в `job_events.detail.delay_seconds`. Full jitter не выбран: все пять попыток могли бы уложиться в доли
секунды и короткий отказ S3 превратился бы в `retry_exhausted`; нижняя граница `d/2` держит суммарное окно 15–30 с
при базе 2 с. После `JOB_MAX_ATTEMPTS` (5) попыток — `failed` с `retry_exhausted`. Постоянные ошибки — сразу
`failed`, без повторов: не декодируется или больше `MAX_IMAGE_PIXELS` по заголовку — `invalid_image`; превышены
время или память рендера, оригинал больше `MAX_UPLOAD_BYTES`, оригинала нет в хранилище, непредвиденная ошибка —
`processing_failed`. В `error_code` — короткий код, в `jobs.last_error` — имя класса ошибки без текста. Все переходы
— с fencing по `lease_token` и не трогают вложение в `ready`.
**Доступ к S3.** Только LB публикует host-порты на loopback. RustFS в internal-сети,
консоль выключена. `s3-init` повторяемо создаёт private bucket, политики/пользователей и
lifecycle очистки незавершённых multipart. API получает только Get/Put/DeleteObject своего
bucket, reconciler — отдельный ключ ListBucket/Get/DeleteObject; root-ключи есть лишь у
`s3`, `s3-init`, `s3-cli`. `s3-init`/`s3-cli` — uid 65534, migrate/reconciler — `init: true`.
**Варианты.** Одно декодирование на задание (`render_variants`): проверка байтов (`MAX_UPLOAD_BYTES`) и пикселей по
заголовку (`MAX_IMAGE_PIXELS`) до декодирования → для JPEG `draft()` до размера optimized (libjpeg сразу уменьшает в
2/4/8 раз) → `ImageOps.exif_transpose(in_place=True)` до расчёта размеров → 16-битные режимы масштабируются в `L`,
палитра с прозрачностью, `LA`, `RGBA` компонуются на белый фон, прочее — `convert("RGB")` → три
`resize(LANCZOS, reducing_gap=3)`. Размеры — от размеров после ориентации по заголовку, целочисленно вниз:
## Критерий → команда → наблюдение → файл
| Вариант | Геометрия | Кодирование | Fixture 320×200 |
Номера ниже — строки этого отчёта, а не дополнительная рубрика. **F** означает SHA
`75b93bbba5f29575d3fca1d013cc7e0770d88082` до PNG-фиксов; **S** — исходную SQLAlchemy-серию,
точный SHA команды находится в её raw. **V** — финальная validation на
`5e49502ae78fa48b992c97418e490666c699726d`, runtime идентичен прошедшему review `7a0ebac…`.
[Новые команды и результаты](evidence/load-validation.md) дополняют сохранённые проверки.
| Критерий | Команда | Наблюдение и применимость | Файл |
| --- | --- | --- | --- |
| `thumbnail` | вписан в 256×256, без увеличения, вниз, минимум 1 px | JPEG `quality=85`, `optimize=True` | 256×160 |
| `crop` | `ImageOps.fit` в 128×128 по центру (`centering=(0.5, 0.5)`), увеличение разрешено | JPEG `quality=85`, `optimize=True` | 128×128 |
| `optimized` | вписан в 1280×1280, без увеличения, вниз, минимум 1 px | WebP с потерями `quality=80`, `method=4` | 320×200 |
| 3.1 Минимум ЛР3 | `make test`; `student-tests/tools/forward_network.py`; `make lb-check`; `make retry-check` | F: smoke, отзыв сессий на двух репликах, NUL/Basic PASS; S: 20×8 запросов с одним ключом, одна копия; потерянный ответ и kill без дублей | [smoke](evidence/forward-final-2026-11-06/smoke.txt), [сеть](evidence/forward-final-2026-11-06/network-regressions.txt), [LB](evidence/sqlalchemy-2026-11-06/grade3/lb-check-rerun.txt), [retry](evidence/sqlalchemy-2026-11-06/grade3/retry.txt) |
| 3.2 Метаданные отдельно от байтов, приватность, stateless API | `make attachments-evidence`; `make limits` | S: внешняя сверка размера/SHA, изображения не в БД/API; F: лимиты, сети, mounts и порты PASS | [размещение](evidence/sqlalchemy-2026-11-06/grade3/storage-layout.txt), [лимиты](evidence/forward-final-2026-11-06/limits.txt) |
| 3.3 `201 ready`, сообщения, checksum, чужому `404` | `make test`; `make student-test` | F: PASS, включая реальные PostgreSQL/RustFS-тесты; V: smoke и 721 собственная проверка прошла (719 + адресный повтор 2 setup errors) | [smoke](evidence/forward-final-2026-11-06/smoke.txt), [492 теста](evidence/forward-final-2026-11-06/offline-checks-rerun.txt), [V smoke](evidence/png-final-2026-11-06/smoke.txt) |
| 3.4 PNG/JPEG, 10 MiB/40 MP, MIME/filename | `make test-faults`; `make student-test PYTEST_ARGS='-q --tb=short student-tests/unit'` | F: граничные файлы, MIME/имена → 4xx; текущие offline-регрессии: оба PNG из ревью → 415, без записи. V: оба файла → 415 через LB, число строк/объектов неизменно; PNG/JPEG скачаны побайтно | [старый suite](evidence/forward-final-2026-11-06/stack-faults.txt), [407 unit](evidence/png-header-fix/unit.txt), [регрессии](evidence/png-header-fix/targeted.txt), [V PNG/JPEG](evidence/png-final-2026-11-06/png-roundtrip.json) |
| 3.5 Upload → остановка принявшей реплики → download | `make scenario SCENARIO=failover-upload` | F: target exited, сосед running, SHA совпал, download через 2,762 с | [JSON](evidence/forward-final-2026-11-06/failover-upload.json) |
| 3.6 Restart с volumes и failover | `make persistence-evidence`; `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | F: данные/сессия сохранены; 130 записей, 0 ошибок, первая запись через 2,883 с | [persistence](evidence/forward-final-2026-11-06/persistence-rerun.txt), [failover](evidence/forward-final-2026-11-06/failover-d4c8d53d7433.txt) |
| Отказ S3 | `make scenario SCENARIO=s3-outage` | F: upload/download 503 за 4,990/5,329 с; текст 201, метаданные/readiness 200; после возврата checksum равен | [JSON](evidence/forward-final-2026-11-06/s3-outage.json) |
| 4.1 Пользовательские ошибки файлов не дают 500 | `make test-faults`; PNG ASGI-регрессии | F: 112 ответов в журнале негативного suite, 0×5xx; битый zlib и повторный IHDR добавлены позднее. V: 7 stack PASS, включая оба PNG; 54 ответа негативного теста, 0×5xx | [stack](evidence/forward-final-2026-11-06/stack-faults.txt), [PNG](evidence/png-header-fix/NOTES.md), [V suite](evidence/png-final-2026-11-06/upload-faults.txt) |
| 4.2 Компенсация, crash и безопасная уборка | `make test-faults`; `make overload-leftovers` | F: COMMIT fault → 503, строка/объект удалены; обе реплики убиты между PUT/COMMIT, свежие/ready сохранены. S: 30 pending убраны после реальных 900 с, 1669 ready/объектов совпали | [отказы](evidence/forward-final-2026-11-06/stack-faults.txt), [grace без сдвига времени](evidence/sqlalchemy-2026-11-06/grade4/overload-leftovers.txt) |
| 4.3 Ограниченная RAM, ≥10 загрузок | `make upload-memory ARGS='--slots 3 --out <новая-серия>'` | S: 36 точек; F: 3 точки, максимум 456,2 MiB, OOM 0, 238×201/2×503. V: 18 точек, 840/840×201, API ≤440 MiB, LB ≤31,1 MiB, OOM 0; 10×40 MP RGBA16 → 201, API ≤270,8 MiB | [S](evidence/sqlalchemy-2026-11-06/grade4/NOTES.md), [F](evidence/forward-port.md#повтор-затронутых-измерений), [V RAM](evidence/png-final-2026-11-06/memory-summary.json) |
| 4.4 Bootstrap/IAM/закрытая консоль/private вне API | `make s3-check` | S: 31 PASS, anonymous GET 403, API ListBucket запрещён, повтор bootstrap ×2 неизменен; конфигурация не менялась | [сырой вывод](evidence/sqlalchemy-2026-11-06/grade3/s3-security.txt) |
| 5.1 Внедрение, dry-run/apply/повтор, защита свежих и ссылок | F: `make reconcile-demo`; V: `python3 evidence/png-final-2026-11-06/concurrent-reconcile.py` | F: 13 PASS; 18 исправлений, повтор 0, ссылки сохранены; алгоритм не менялся. V: 3341×201 при 67 проходах, lost_ready=0, независимый SHA-аудит PASS | [demo](evidence/forward-final-2026-11-06/reconcile-demo/demo.json), [V load](evidence/png-final-2026-11-06/concurrent-reconcile/under-load.json) |
| 5.2 Стоимость обхода | `make reconcile-cost ARGS='--out <новая-серия>'` | 27 замеров на `3402fd6…`, 1k/10k/30k/100k; страницы и память подтверждены, линейное время отвергнуто | [методика](evidence/sqlalchemy-2026-11-06/track5/NOTES.md), [сырьё](evidence/sqlalchemy-2026-11-06/track5/measurements/cost/) |
Метаданные (EXIF, ICC, XMP) в варианты не пишутся: кодеры Pillow 13 берут их только из явных параметров `save`,
а мы их не передаём (`student-tests/unit/test_renderer.py` проверяет и `getexif()`, и `info`). Альфа в `optimized`
тоже на белом — один источник для трёх вариантов; уменьшения каждого маленького файла WebP не обещает. Примеры:
17×1000 → thumbnail 4×256, optimized 17×1000; 3000×2 → 256×1 и 1280×1; JPEG 4000×3000 → 256×192 и 1280×960; EXIF 6
400×200 → 128×256 и 200×400. `ready` выставляет та же транзакция, что пишет строки трёх вариантов: частичного
набора в API не бывает (`test_partial_variant_set_is_never_published`).
## Отказы: наблюдаемое время и потери
**Пределы worker.** Рендер — адаптер `ProcessVariantRenderer` порта `VariantRenderer`: `WORKER_CONCURRENCY` слотов,
слот — `ProcessPoolExecutor(max_workers=1, max_tasks_per_child=RENDER_TASKS_PER_CHILD=100)` (forkserver), в
процессе рендера `RLIMIT_AS = RENDER_MEMORY_MB` (448 MiB). Ожидание результата — `asyncio.wait_for(…,
RENDER_TIMEOUT_SECONDS=30)`; таймаут → `kill_workers()` этого слота и новый процесс, `processing_failed`;
`MemoryError` в процессе рендера → `processing_failed`; процесс убит снаружи → временная ошибка; отменённый рендер
(потеря аренды, остановка) тоже убивает свой процесс. Слот на процесс, а не общий пул: убийство по таймауту не
задевает соседнее задание. Замеры в образе: процесс рендера после импорта Pillow — 46 МБ адресного пространства,
рендер трёх вариантов 8000×5000 — пик 258 МБ (RGB) и 398 МБ (RGBA); с пределом 300 МБ RGBA-рендер получает
`MemoryError`. Поэтому `RENDER_MEMORY_MB=448` покрывает любое 8-битное изображение до 40 Мпикс, а предел контейнера
`WORKER_MEMORY=1g ≥ 2 × 448 MiB + ~120 MiB` самого worker. Prefetch канала = `WORKER_CONCURRENCY` = число слотов:
в полёте у процесса не больше двух заданий.
Основная таблица — **F**, проект `hlpipe-lab4-forward-final-20261106`.
Времена — отдельные наблюдения, не SLA. Потерями считаются подтверждённые клиенту данные;
намеренно повреждённые байты в demo отдельно отмечены. Состояния контейнеров сохранены
в JSON/inspect и выводе хуков; неизвестные длительности не заменены нулём.
**Чтение.** `GET /attachments/{id}` отдаёт любой статус, кроме внутреннего `pending`, с вариантами опубликованной
версии одним запросом (`jsonb_agg` по PK вариантов). `/content`: посторонний — `404`; не `ready` — `409 conflict`
для любого `variant`, включая `original`; `original` — `original_key` с типом оригинала; `thumbnail` — вариант;
`thumbnail`, `crop`, `optimized` — варианты опубликованной версии; варианта нет у опубликованной версии (вложение,
ставшее `ready` в лабе 4) — `404`; иное значение `variant` — `400`. Сообщение со ссылкой на `failed` —
`409`, на `queued`/`processing` — `201`; повтор по `Idempotency-Key` возвращает исходный ответ, даже если
вложение потом стало `failed`.
**Готовность и SIGTERM.** `/health/ready` реплик API зависит только от PostgreSQL, как в лабе 4: брокер развязан
outbox-ом, а при недоступном S3 upload и скачивание отвечают `503` от приложения, тексты работают. Relay и worker
проверяются heartbeat-файлом, который обновляется, пока жив цикл событий и брокер отвечает на ping (от PostgreSQL и
S3 не зависит — иначе worker не стартовал бы при временно недоступном S3). SIGTERM: worker отменяет consumer, ждёт
задачи до 5 с, закрывает канал (неподтверждённые сообщения возвращаются в очередь); relay завершает циклы и
закрывает соединение; оба выходят с кодом 0 за 0,5 с (`evidence/pipeline-stand.txt`).
**Окна отказа** (`contracts/attachment-states.md`). Точки падения задаёт `FAULT_POINT` только в
`infra/compose.faults.yaml` (там же `restart: "no"`, аренда 5 с, база backoff 1 с); падение — `os._exit(137)` после
сброса журналов, без какой-либо дальнейшей работы; порт `Faults` вызывается в обработчиках зоны:
| Окно | Точка `FAULT_POINT` (процесс) | Что лежит после сбоя | Кто восстанавливает | Сценарий |
| --- | --- | --- | --- | --- |
| 1: после staging, до записи задания | — (API) | невидимая строка `pending` и объект `staging/`, `202` не отдан | компенсация сразу; уборка намерений лабы 4 после grace | `make upload-faults` (лаба 4) |
| 2: после `COMMIT`, до publish | `after_commit_before_publish` (relay: строка взята `FOR UPDATE`, publish не отправлен) | строка outbox без `published_at`, очередь пуста, вложение `queued` | relay после рестарта, тот же `job_id` | `crash_commit_publish` |
| 3: после publish, до confirm/`published_at` | `after_publish_before_confirm` (relay: confirm получен, `published_at` не записан) | сообщение в очереди, строка не помечена | relay публикует повторно, вторая копия — `duplicate_noop` | `crash_publish_confirm` |
| — после захвата, до побочных эффектов | `after_claim_before_side_effect` (worker) | `processing`, живая аренда, S3 пуст | redelivery видит живую аренду → `ack`; relay возвращает задание по истечении аренды | трек 2 |
| 4: после записи S3, до `COMMIT` результата | `after_s3_write_before_commit` (worker) | объекты трёх вариантов и оригинала, строк вариантов нет | relay возвращает аренду, попытка 2 пишет те же ключи и фиксирует | `crash_after_s3_before_commit` |
| 5: после `COMMIT`, до `ack` | `after_commit_before_ack` (worker) | `ready`, сообщение не подтверждено | redelivery видит `done` → `duplicate_noop` и `ack` | `crash_after_commit_before_ack` |
| зависший держатель | `stall_after_claim` (worker: один раз спит `FAULT_STALL_SECONDS`=15 с без продления) | аренда истекает | relay возвращает задание, вторая попытка → `ready`; проснувшийся держатель не продлевает аренду → `fenced` | `lease_expiry_fencing` |
Окно 3 воспроизводится состоянием, а не моментом: FastStream ждёт confirm внутри `publish`, поэтому процесс падает
уже после confirm, но до записи `published_at`; для системы это то же — брокер знает о сообщении, PostgreSQL нет.
At-least-once доставки + идемпотентный эффект по ключу `(attachment_id, pipeline_version, variant)` + fencing по
`lease_token` = один опубликованный результат. Это не exactly-once: окна 3 и 5 дают повторные доставки, их гасит
эффект, а не брокер.
**Топология брокера** (`infra/rabbitmq/definitions.json`, импорт на каждой загрузке): vhost `messenger`
(`default_queue_type: quorum`); exchange `attachments` (direct) → `attachments.process` (quorum, durable);
`attachments.dlx` (fanout) → `attachments.process.dlq` (quorum); политика `attachments-process`:
`dead-letter-exchange=attachments.dlx`, `dead-letter-strategy=at-least-once`, `overflow=reject-publish`,
`delivery-limit=10`; DLQ — `max-length=100000`. DLX и delivery-limit заданы политикой, поэтому клиенты делают
только пассивный declare и не получают `PRECONDITION_FAILED`. Права (`evidence/topology.txt`): `messenger-api`
(relay) — только запись в `attachments`, `messenger-worker` — только чтение `attachments.process`,
`messenger-ops` — оператор; `guest` нет. В `rabbitmq.conf`: `consumer_timeout` 300 с (больше аренды 60 с),
`vm_memory_high_watermark` 256 MiB, запрет transient-очередей и global QoS.
**Роли и сервисы** (`compose.yaml`; сети `edge` и `backend` с `internal: true`):
| Роль | Сервис | Версия / digest | Health / readiness | Volume | Сеть / порт | Credentials |
| --- | --- | --- | --- | --- | --- | --- |
| load_balancer | `lb` | `haproxy:3.2.26-alpine@sha256:58938405…`, uid 99, `read_only` | `/healthz` :8404; реплики — `GET /health/ready` | нет | `edge` + `backend`; `127.0.0.1:${LB_HTTP_PORT:-8080}`, `127.0.0.1:${LB_STATS_PORT:-8404}` | нет |
| api ×`API_REPLICAS` | `api` | сборка из `Dockerfile`, uid 10001, `read_only` | `GET /health/ready` (PostgreSQL) | нет | `backend`, без портов | `database_url`, `cache_url`, `cursor_secret`, ключ API S3 через `*_FILE`; брокера нет |
| broker | `broker` | `rabbitmq:4.1.8-management-alpine@sha256:54ef5ff5…`, uid 100, `hostname: broker`, `read_only`, `cap_drop: ALL` | `rabbitmq-diagnostics -q check_port_connectivity` | `broker-data:/var/lib/rabbitmq` | `backend` + `edge`; AMQP 5672 внутри; UI `127.0.0.1:${BROKER_MANAGEMENT_PORT:-15672}` | definitions с хешами паролей — secret `rabbitmq_users`; пароль оператора — `rabbitmq_ops_password` |
| outbox relay | `relay` | образ приложения, `python -m messenger.relay`, `init`, `read_only` | heartbeat `/tmp/heartbeat` моложе 30 с | нет | `backend`, без портов | `database_url`, `broker_url` ← `broker_url_api`, ключ API S3 |
| worker | `worker` | образ приложения, `python -m messenger.worker`, `init`, `read_only` | heartbeat `/tmp/heartbeat` моложе 30 с | нет | `backend`, без портов | `database_url`, `broker_url` ← `broker_url_worker`, ключ worker S3 |
| postgres | `postgres` | `postgres:17.11-alpine@sha256:266d3c25…`, uid 70 | `pg_isready` | `pgdata` | `backend` | `postgres_password` через `POSTGRES_PASSWORD_FILE` |
| s3 | `s3` | `rustfs/rustfs:1.0.4@sha256:ed9210d6…`, uid 10001, консоль выключена | `curl /health/ready` | `s3data` | `backend`, :9000 без публикации | root-ключи через `RUSTFS_*_FILE` |
| bootstrap S3 | `s3-init` | `rustfs/rc:v0.1.36@sha256:ab024bfe…` | код выхода 0 | нет | `backend` | root-ключи, ключи API и worker (создаёт пользователей) |
| bootstrap схемы | `migrate` | образ приложения, `restart: "no"` | код выхода 0 | нет | `backend` | `database_url` |
| сессии (кэш) | `valkey` | `valkey/valkey:8.1.11-alpine@sha256:2602ace2…`, uid 999 | `valkey-cli ping` | `valkeydata` (AOF) | `backend` | `valkey.conf` |
| CLI S3 и нагрузка | `s3-cli` (профиль `tools`), `k6` (профиль `bench`) | как в лабе 4 | нет | нет | `backend` / `edge` | как в лабе 4 |
Bootstrap: схема — `migrate` (advisory lock, повтор без изменений); bucket, политики `messenger-api`
(`infra/s3/api-policy.json`) и `messenger-worker` (`infra/s3/worker-policy.json`: чтение `staging/`, `originals/`,
`variants/`, запись `originals/` и `variants/`), пользователи и lifecycle — `s3-init` (`--ignore-existing`, повтор
без изменений, самопроверка политик); топология и пользователи брокера — definitions на загрузке узла
(идемпотентный импорт; ротация пароля — удалить `secrets/rabbitmq_<роль>_password` и `broker_url_<роль>`,
`make secrets`, `docker compose up -d broker relay worker`). Лимиты: broker 1/512m, relay 0.5/192m, worker
2/1g (два процесса рендера по 448 MiB и сам worker), остальное как в лабе 4; `make limits` проверяет политику секретов, volumes, сетей и портов
(`evidence/limits.txt`).
**Соответствие `.env.example` реальной конфигурации:**
| `.env.example` | В решении | Комментарий |
| --- | --- | --- |
| `APP_*`, `SESSION_*`, `DATABASE_URL_FILE`, `CACHE_URL_FILE`, `API_REPLICAS`, `IDEMPOTENCY_TTL_SECONDS`, `S3_*`, `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS` | как в лабе 4 | |
| `BROKER_URL_FILE=/run/secrets/broker_url` | тот же у `relay` и `worker` | разные secrets: `broker_url_api` и `broker_url_worker`; у API нет |
| `WORKER_CONCURRENCY=2` | тот же | prefetch канала consumer и параллельные рендеры одного worker |
| `JOB_MAX_ATTEMPTS=5` | тот же | предел попыток; последняя неудача — `retry_exhausted` |
| `JOB_TIMEOUT_SECONDS=60` | тот же | аренда захваченного задания; меньше `consumer_timeout` 300 с |
| `STAGING_RETENTION_SECONDS=86400` | тот же (настройка relay) | staging `ready`-вложения relay удаляет сразу после публикации, `failed` — через `STAGING_RETENTION_SECONDS` после перехода в `failed` (до этого возможен replay) |
| — | `BROKER_MANAGEMENT_PORT`, `JOB_BACKOFF_BASE_SECONDS`, `OUTBOX_POLL_SECONDS`, `SWEEP_INTERVAL_SECONDS`, `WORKER_CPUS`, `WORKER_MEMORY`, `PIPELINE_DB_POOL_MAX_SIZE` | UI брокера; база backoff 2 с; опрос outbox 1 с; возврат аренд и уборка staging 5 с; лимиты worker; пул PostgreSQL relay и worker |
| — | `RENDER_TIMEOUT_SECONDS=30`, `RENDER_MEMORY_MB=448`, `RENDER_TASKS_PER_CHILD=100`, `WORKER_MEMORY=1g` | время рендера (процесс убивается), адресное пространство процесса рендера, задач на процесс; `WORKER_MEMORY ≥ WORKER_CONCURRENCY · RENDER_MEMORY_MB` + ~120 MiB |
| — | `FAULT_POINT`, `FAULT_STALL_SECONDS`, `FAULT_RENDER_TIMEOUT_SECONDS`, `FAULT_RENDER_MEMORY_MB`, `FAULT_STAGING_RETENTION_SECONDS` | только в `infra/compose.faults.yaml` (короткие аренда и backoff, `restart: "no"`), никогда в основном стенде; suite переводит relay и worker в этот режим и возвращает обратно |
| — | прочие `LB_*`, `API_*`, `PG_*`, `UPLOAD_*`, `S3_*_TIMEOUT_SECONDS`, `MALLOC_MMAP_THRESHOLD_` | как в лабе 4 |
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| Воздействие / команда | Реально затронутый контейнер или объект | Наблюдение, время | Потери / файл |
| --- | --- | --- | --- |
| Публичный smoke | `make test BASE_URL=http://localhost:18085` | `PASS: lab5 public API scenario` (upload → `202 queued`, сразу сообщение `text=""` с вложением → `201`, `ready` от bob, оригинал побайтно `image/png`, eve `404`, один вариант `thumbnail` 256×160, настоящий JPEG той же длины и SHA-256, весь минимум lab2–lab4) | `evidence/smoke.txt` |
| `make check` / `make validate` / `make lint` | `make check`; `make validate` в venv с `requirements-dev.txt`; `make lint` | `PASS: offline skeleton structure…`; `PASS: full OpenAPI 3.1 and JSON Schema validation`; ruff, формат, ty — `All checks passed!` | `evidence/contract-checks.txt` |
| Собственные тесты | `make student-test` | `417 passed, 1 skipped` (предел `RLIMIT_AS` — только Linux; 15 проверок стенда под маркером `stack` — отдельно): pipeline против PostgreSQL, восстановление после внедрённых падений, продление аренды, replay и retention, пул процессов рендера, три варианта, jitter, CLI оператора, адаптеры против RabbitMQ и RustFS, контракт сообщения, архитектура | `evidence/student-tests.txt` |
| **3.1** `202` только после устойчивого staging и сохранения задания; остановка API после ответа не теряет работу | `make level3` (`worker_down_broker_restart`), `make pipeline-evidence`; тесты `test_attachments.py`, `test_upload_consistency.py`, `test_pipeline.py` | ответ — снимок `queued`, в БД ключ `staging/<id>`, задание и строка outbox; отказ фиксации после записи staging → `503`, нет ни строки, ни задания, ни объекта; после `202` перезапущены обе реплики API и relay — задание одно в очереди и доходит до `ready` | `evidence/level3.json`, `evidence/pipeline-stand.txt`, `evidence/student-tests.txt` |
| **3.2** Отдельные broker и worker в общем стенде; durable, at-least-once, подтверждение после эффекта | `make topology`; `make pipeline-evidence`; `test_rabbitmq.py` | `attachments.process` и `.dlq` — `quorum`, `durable`, политики применены; один consumer `ack_required=true`, `prefetch_count=2`; сообщение в очереди: `delivery_mode: 2`, `message_id` = `job_id`, тело — ровно 7 полей `jobs.schema.json`; `ack` только после `COMMIT` (ошибка обработки → `nack` → повторная доставка до успеха); сообщение не по схеме → DLQ; учётка worker не может публиковать | `evidence/topology.txt`, `evidence/pipeline-stand.txt`, `evidence/student-tests.txt` |
| **3.2** Недоступность worker не заставляет API делать resize синхронно | `make pipeline-evidence`, `worker_down_broker_restart` | worker остановлен: upload `202 queued`, `/content` (`original` и `thumbnail`) → `409`, сообщение с вложением `201`, текст и история работают, вложение остаётся `queued`, задание лежит в очереди (`messages_ready=1`) | `evidence/pipeline-stand.txt`, `evidence/level3.json` |
| **3.3** Состояния `queued/processing/ready/failed`; оригинал неизменен, thumbnail по контракту | `make test`, `smoke_pipeline`, `test_pipeline.py`, `test_renderer.py` | переходы видны в API и `job_events` (`enqueued → claimed → done`); оригинал из `originals/<id>` побайтно равен загруженному; thumbnail 256×160 JPEG, длина и SHA-256 равны метаданным; инвариант `bytes_match_metadata` — PASS | `evidence/smoke.txt`, `evidence/level3.json`, `evidence/student-tests.txt` |
| **3.4** Ограниченный retry, финальное `failed` с безопасным `error_code` | `retry_exhausted`, `s3_outage_recovers` (`make level3`); `test_pipeline.py` | точка `transient_error`: задание `failed`, `attempt = 5 = JOB_MAX_ATTEMPTS`, `error_code = retry_exhausted`, `/content` и сообщение со ссылкой → `409`; S3 остановлен во время обработки → вложение `queued` с `attempt = 2`, после возврата S3 — `ready`; нечитаемый оригинал → `invalid_image` с `attempt = 1`; следующая попытка отложена на базу backoff; инвариант `bounded_attempts` — PASS | `evidence/level3.json`, `evidence/student-tests.txt` |
| **3.4** Повтор одной job не создаёт второго набора вариантов | `duplicate_after_ready`; `test_pipeline.py` | копия сообщения после `ready` → `duplicate_noop`, метаданные и строки вариантов до и после равны; две копии одновременно → один `done` и один `duplicate_noop`, одна строка варианта, `claims = 1`; опоздавший держатель аренды → `fenced`, вариантов не добавил; инвариант `single_effect` — PASS | `evidence/level3.json`, `evidence/student-tests.txt` |
| **3.5** Демонстрация: worker остановлен → upload `202` → сообщение → рестарт API → worker → `ready`; задание переживает рестарт broker с volume | `make level3` (`worker_down_broker_restart`) | хронология с ID без токенов: worker остановлен 22:20:24.58; upload `202 queued` (`01a18499-a689…`); `/content` `409`; сообщение `201` (`01a18499-a698…`); в очереди `[1, 0]`; обе реплики API и relay перезапущены; broker перезапущен с volume — в очереди снова `[1, 0]`; worker запущен 22:20:49.24, `ready` с `thumbnail` 22:20:49.42 | `evidence/level3.json` |
| **3.5** Минимум lab4: persistence | `make persistence-evidence` | `PASS: persistence …`; `StartedAt` у `lb`, обеих `api`, `relay`, `worker`, `postgres`, `valkey`, `s3`, `broker` новее, контейнеры те же, hostname брокера `broker` | `evidence/persistence.txt` |
| **3.5** Минимум lab4: failover | `make failover-evidence` | `PASS: failover …`: 2 реплики до отказа, 134 записи, 0 ошибок, первая запись через 2,85 с; цель `db66b246dcf8` в `exited`, в её журнале сигнал, окно readiness `503`, выход; `make restore` вернул реплику | `evidence/failover.txt` |
| Минимум lab4: download через другую реплику, недоступный S3, приватность, негативный suite, политика | `make scenario SCENARIO=failover-upload`, `SCENARIO=s3-outage`, `make s3-check`, `make upload-faults`, `make limits` | upload принят `db66b246dcf8`, после `ready` и её остановки — скачивание через `6f688eb249b1` за 2,87 с, SHA-256 равен; S3 остановлен: upload и `/content` `503` за 4,5–4,7 с, метаданные, текст и readiness работают; `RESULT: PASS`; 5 проверок стенда, 0 × `5xx`; политика портов, секретов и сетей — PASS | `evidence/failover-upload.json`, `evidence/s3-outage.json`, `evidence/s3-security.txt`, `evidence/upload-faults.txt`, `evidence/limits.txt` |
| Инварианты suite уровня «3» | `make suite-preflight && make level3` | 6/6 сценариев PASS; `terminal`, `single_effect`, `no_ready_rollback`, `monotonic_publication`, `bytes_match_metadata`, `bounded_attempts`, `no_orphans` (очереди пусты, outbox опубликован, staging `ready` убран, лишних писем в DLQ нет), `no_lost_202` — PASS | `evidence/level3.json` |
| **4.1** Crop 128×128 и optimized WebP по контракту, параметры качества и удаления метаданных | `make level4` (`image_matrix`, `smoke_pipeline`), `test_renderer.py`, `test_attachments.py` | 17 изображений матрицы (RGB, RGBA, палитра с tRNS, серые 8/16 бит, CMYK, EXIF 6 и 3, 1×1, 3000×2, 4000×3000, ровно 10 MiB) → `ready` с `crop`, `optimized`, `thumbnail`; у каждого варианта реальные размеры из SOF/VP8 равны метаданным и manifest, длина и SHA-256 равны отдаваемым байтам; fixture: 256×160, 128×128, 320×200; в вариантах нет EXIF, ICC, XMP; частичный набор не публикуется | `evidence/level4.json`, `evidence/student-tests.txt` |
| **4.1** Пределы по байтам, пикселям, времени и памяти worker | `make level4` (`image_matrix`, `worker_limits`), `test_render_pool.py`, `test_renderer.py` | вход: 10 485 761 B, 8001×5000 и 10000×5000 → `413`, битые и не-изображения → `415`; worker: PNG 8000×5000 при `RENDER_TIMEOUT_SECONDS=0,5` и при `RENDER_MEMORY_MB=200` → `failed processing_failed` с `attempt 1`, контейнер worker `running`; со штатными пределами тот же файл → `ready`, пик `memory.peak` 379 MiB при `memory.max` 1024 MiB; в тестах таймаут убивает процесс и освобождает слот, падение процесса рендера — временная ошибка, `MemoryError` — постоянная | `evidence/level4.json`, `evidence/student-tests.txt` |
| **4.2** Transactional outbox; crash между `COMMIT` и publish, восстановление без нового задания | `make level4` (`crash_commit_publish`, `crash_publish_confirm`), `test_recovery.py` | relay с `after_commit_before_publish` → exit 137, строка outbox `published=false`, очередь `[0, 0]`, вложение `queued`; relay перезапущен без точки → `ready` с тем же `job_id`, outbox опубликован; `after_publish_before_confirm` → exit 137, строка не помечена, после рестарта повторная публикация, вторая копия — `duplicate_noop` | `evidence/level4.json`, `evidence/student-tests.txt` |
| **4.3** Backoff с jitter, постоянные и временные ошибки | `make level4` (`retry_backoff_jitter`, `s3_outage_recovers`, `poison_image`, `retry_exhausted`), `test_pipeline_domain.py`, `test_pipeline.py` | задержки попыток 2–5 при базе 1 с: 0,69; 1,74; 2,83; 7,55 с — доли верхней границы 0,69; 0,87; 0,71; 0,94 в `[0,5; 1]` (`make replay` в `evidence/operator.txt`: 0,55; 1,71; 2,20; 4,25 с); S3 остановлен → `queued`, затем `ready`; таймаут/память рендера и пропавший оригинал → `processing_failed`, нечитаемое изображение → `invalid_image`, оба с `attempt 1`; 200 случайных задержек лежат в `[d/2, d)` | `evidence/level4.json`, `evidence/student-tests.txt` |
| **4.3** DLQ, реестр `failed` и безопасный явный replay; повтор не исполняет дубль успешной job | `make level4` (`replay_failed`, `malformed_message_dead_lettered`, `failed_retention`); `make failed`, `make replay ID=…`, `make dlq`; `test_recovery.py` | `retry_exhausted` → `replay` → `{"result": "replayed"}` → `ready` (журнал `… failed, replayed, claimed, done`); повторный replay `ready` → `{"result": "noop"}`, снимок вариантов равен, событие `replay_noop`; staging `failed` хранится до retention, после него replay → `expired`; сообщение не по схеме → DLQ, видно `make dlq` без извлечения | `evidence/level4.json`, `evidence/operator.txt` |
| **4.4** Остановка worker после записи объекта, но до `ack`; повтор завершает тот же результат | `make level4` (`crash_after_s3_before_commit`, `crash_after_commit_before_ack`), `test_recovery.py` | `after_s3_write_before_commit` → exit 137, вложение `processing`, строк вариантов 0; после запуска worker — `ready` на попытке 2, те же ключи объектов; `after_commit_before_ack` → exit 137, вложение уже `ready`; redelivery → `duplicate_noop`, строки вариантов до и после равны | `evidence/level4.json`, `evidence/student-tests.txt` |
| **4.4** Timeout/lease для зависшего `processing`, ограниченная конкуренция/prefetch, очистка staging после фиксации | `make level4` (`lease_expiry_fencing`), `make topology`, инвариант `no_orphans`; `test_recovery.py` | `stall_after_claim` (15 с при аренде 5 с): журнал `claimed(1), lease_expired(2), claimed(2), done(2), fenced(1)`, снимок результата до и после пробуждения равен; долгий рендер (2,5 с при аренде 1 с) продлевает аренду и не возвращается relay; consumer `prefetch_count=2` = `WORKER_CONCURRENCY` = слоты рендера; staging `ready` убран (`staging_left` пуст), `failed` — по retention | `evidence/level4.json`, `evidence/topology.txt` |
| Инварианты suite уровня «4» | `make suite-preflight && make level4` | 17/17 сценариев PASS за 6 мин 14 с; `terminal`, `single_effect`, `no_ready_rollback`, `monotonic_publication`, `bytes_match_metadata` (28 `ready`), `bounded_attempts`, `no_orphans` (очередь `[0, 0]`, в DLQ ровно ожидаемое письмо), `no_lost_202` (33 из 33) — PASS | `evidence/level4.json` |
| Сценарий защиты п. 4 | `make level4` или по одному: `pipeline_suite.py --only crash_after_commit_before_ack,crash_commit_publish,replay_failed` | crash после side effect до `ack`, разрыв `COMMIT`/publish и replay `failed` — строки 4.2–4.4 | `evidence/level4.json` |
| Трек 2 | — | заполняется изменением трека 2: versioned pipeline, fault-injection suite одной командой, инварианты | — |
| `scenario failover-upload` | API `d4c8d53d7433` exited; `da922ab2ea09` running | Хук 2,734 с; download через 2,762 с от старта | Байты совпали; [JSON](evidence/forward-final-2026-11-06/failover-upload.json) |
| `test-failover` | API `d4c8d53d7433`, подтверждён exited | 130 успешных записей, 0 failed_attempts; первая через 2,883 с | Дубликатов/потерь не обнаружено; [inspect и тест](evidence/forward-final-2026-11-06/failover-d4c8d53d7433.txt) |
| `persistence-evidence` | API ×2, LB `ea6930f64089`, PG `3f3a870d89c0`, Valkey `07ea16e2fcfe`, S3 `5921e788f03d`; StartedAt изменились | Вся команда 13,179 с; это не точный интервал недоступности | Однократное чтение после hook сохранило данные/сессию; [до/после](evidence/forward-final-2026-11-06/persistence-rerun.txt) |
| `scenario s3-outage` | S3 `5921e788f03d` exited | 503: upload 4,990 с, download 5,329 с; healthy через 5,760 с после старта | Готовый файл сохранился; текст 201; [JSON](evidence/forward-final-2026-11-06/s3-outage.json) |
| `make test-faults`, PostgreSQL stop | Сервис postgres своего project; отдельного inspect в suite нет | 503 за 0,002–0,015 с; готовность через 2,1 с после старта | Прежний токен работает, 40 регистраций через 2 реплики без рестарта API; [stack](evidence/forward-final-2026-11-06/stack-faults.txt) |
| `make test-faults`, Valkey stop | Сервис valkey своего project; отдельного inspect в suite нет | Живой токен 200 за 0,005 с; неизвестный 401 за 0,003 с; logout 503, после старта 204 | Отзыв не потерян; время восстановления не измерено; [stack](evidence/forward-final-2026-11-06/stack-faults.txt) |
| COMMIT fault после PUT | Триггер в синтетическом сценарии | 503; сразу строка отсутствует и HEAD 404; audit compensation | Готовые не затронуты; [stack](evidence/forward-final-2026-11-06/stack-faults.txt) |
| SIGKILL между PUT/COMMIT | По очереди API `da922ab2ea09`, `d4c8d53d7433` | Клиент 502; pending + объект. После сдвига за grace удаление через 26,1/1,5 с | Свежий остаток сохранён; ready в сообщении скачан с тем же SHA; [stack](evidence/forward-final-2026-11-06/stack-faults.txt) |
| Обрыв / зависание тела | 256 KiB из 5 MiB / 1 KiB | Обрыв: 400 в журнале, нет intent; stall: 503 через 8,02 с | Новых видимых вложений нет; [stack](evidence/forward-final-2026-11-06/stack-faults.txt) |
| Реальное ожидание grace, серия S | 30 pending: 27 после перегрузки, 3 после S3-outage | Наблюдение 847,812 с уже существовавших остатков; возраст не меняли, grace 900 с | 30 audit abandoned, затем 1669 ready = 1669 объектов; [вывод](evidence/sqlalchemy-2026-11-06/grade4/overload-leftovers.txt) |
| Reconciler demo, порча обеих сторон | 3 orphan, 9 ready с потерянными/изменёнными байтами, 6 pending | Apply: 18 действий; повтор 0; полный demo 256,6 с | 9 ready и 6 ссылок сохранены, байты сами не восстанавливаются; [demo](evidence/forward-final-2026-11-06/reconcile-demo/demo.json) |
| SIGTERM / S3 outage сверки | Одноразовый reconciler; S3 paused / остановлен | SIGTERM: 0,1 с, exit 143, lock освобождён; S3 outage: exit 1 за 2,32 с | Состояние не изменилось при outage; [demo](evidence/forward-final-2026-11-06/reconcile-demo/demo.json) |
## Эксперименты и отказы
`failover-upload.json` содержит `restored=false`: сценарий сам не возвращал target;
[отдельный restore](evidence/forward-final-2026-11-06/restore.txt) возвращает обе реплики.
В конце фазы F все три её project остановлены, шесть постоянных volumes сохранены:
[shutdown-state](evidence/forward-final-2026-11-06/shutdown-state.txt).
Отчётный этап Docker не использовал. Состояние финальной validation-фазы и сохранённые
volumes зафиксированы отдельно в [аудите](evidence/load-validation.md).
Стенд: 2 реплики `api` (1 CPU, 512 MiB), worker 2 CPU / 1 GiB, relay 0.5 CPU / 192 MiB, RabbitMQ 1 CPU /
512 MiB, RustFS 1 CPU / 512 MiB, PostgreSQL 2 CPU / 1 GiB; Docker Desktop VM 16 CPU, 7.65 ГиБ, параллельно
работали стенды других лаб. Данные — синтетические пользователи и fixture `sample.png` (111 817 B). Сценарии
suite идут с `infra/compose.faults.yaml` у relay и worker (аренда 5 с, база backoff 1 с, опрос outbox 0,5 с).
## Память и запись сообщений
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| Worker остановлен, upload и сообщение | `202 queued`, `409` на `/content`, сообщения работают, задание в очереди | так и есть; `messages_ready=1` | `ready` через 0,2 с после запуска worker; потерь нет |
| Рестарт обеих реплик API и relay после `202` | задание не теряется и не дублируется | в очереди одна копия до и после | потерь нет |
| `scripts/broker.sh restart` при остановленном worker | durable сообщение переживает рестарт | `[1, 0]` до и после, имя узла `rabbit@broker` неизменно | брокер healthy за ~9 с; потерь нет |
| Повторная доставка выполненной job (`rabbitmqadmin publish` той же копии) | no-op с `ack`, результат не меняется | `duplicate_noop`, снимок вариантов равен | — |
| S3 остановлен во время обработки | временная ошибка, `queued`, повтор | `attempt 2`, статус `queued`; после возврата S3 — `ready` | сценарий 13,8 с; потерь нет |
| Каждая попытка — временная ошибка (`FAULT_POINT=transient_error`) | ровно 5 попыток, `failed retry_exhausted` | `attempt 5`, `retry_exhausted`, `409` на `/content` и в сообщении | 22,9 с до `failed`; бесконечного повтора нет |
| Битый PNG (обрезан после IDAT) | `415` на входе или `invalid_image` без повторов | `415` на входе (API проверяет файл до `202`); с подменой staging в тесте — `invalid_image`, `attempt 1` | — |
| Сообщение не по `jobs.schema.json` | в DLQ, worker жив | DLQ +1, очередь пуста (`test_rabbitmq.py`) | — |
| Аренда истекла, старый держатель пытается зафиксировать | relay возвращает задание, старый — `fenced` | `queued`, `attempt 2`, затем `ready`; старая фиксация → `fenced`, вариантов не добавила (`test_pipeline.py`) | следующий проход relay (5 с) |
| Брокер не подтвердил публикацию | строка outbox остаётся | `published_at IS NULL`, после восстановления публикуется (`test_pipeline.py`) | следующий опрос; потерь нет |
| SIGTERM worker и relay | выход ≤10 с, код 0, unacked в очередь | 0,5 с, код 0 | — |
| Перезапуск LB, API, relay, worker, PostgreSQL, Valkey, S3, broker с volumes | данные, сессия, вложение и байты на месте | `PASS: persistence …`, все `StartedAt` новее (повтор на `0b85edf`) | хранилища 00:33:04, relay и worker 00:33:22; потерь нет |
| Остановка реплики API под записью | запись ≤10 с, без дублей | 3,0 с, 133 записи, 0 ошибок (повтор на `0b85edf`) | ≤3 с; потерь нет |
| **4** Relay падает после взятия строки outbox, до publish (`after_commit_before_publish`) | exit 137, строка не опубликована, очередь пуста; после рестарта relay — `ready` без нового задания | exit 137, `published=false`, `[0, 0]`, `queued`; после запуска relay — `ready`, тот же `job_id` | сценарий 17,5 с вместе с рестартом; потерь нет |
| **4** Relay падает после publish, до записи `published_at` | повторная публикация, дубль гасится | exit 137, строка не помечена; журнал `enqueued, claimed, done, duplicate_noop` | 15,7 с; потерь и второго эффекта нет |
| **4** Worker падает после записи объектов в S3, до `COMMIT` | строк нет; повтор пишет те же ключи и фиксирует | exit 137, `processing`, 0 строк вариантов; `ready` на попытке 2, варианты совпадают с метаданными | 23,1 с (аренда 5 с + проход relay); потерь нет |
| **4** Worker падает после `COMMIT`, до `ack` | `ready` уже есть; redelivery — no-op | exit 137, `ready`; redelivery → `duplicate_noop`, строки вариантов равны | 17,5 с; потерь нет |
| **4** Worker завис после захвата на 15 с при аренде 5 с | relay возвращает задание, вторая попытка → `ready`, старый держатель — `fenced` | `claimed(1), lease_expired(2), claimed(2), done(2), fenced(1)`; снимок до и после пробуждения равен | 40,0 с (включая ожидание пробуждения); перезаписи нет |
| **4** Рендер 40 Мпикс при `RENDER_TIMEOUT_SECONDS=0,5` и при `RENDER_MEMORY_MB=200` | `failed processing_failed` без повторов, worker жив | оба — `processing_failed`, `attempt 1`, контейнер `running`; со штатными пределами — `ready`, пик 379 MiB из 1024 MiB | 27,8 с на три загрузки |
| **4** Каждая попытка — временная ошибка, задержки | задержки в `[d/2, d]`, разные доли | 0,69; 1,74; 2,83; 7,55 с при базе 1 с | 35,2 с до `failed` |
| **4** Replay `failed`, затем повторный replay | `failed → queued → ready`; повтор для `ready` — `noop` без публикации | `replayed` → `ready` за <6 с; `noop`, событие `replay_noop`, варианты не изменились | 44,6 с вместе с исчерпанием попыток |
| **4** Retention staging `failed` (1 с в сценарии) | staging хранится до retention, затем удаляется; replay → `expired` | staging был, удалён, `{"result": "expired"}`, статус `failed` не изменился | 41,8 с вместе с исчерпанием попыток |
**Память S, до позднего переноса и PNG-фиксов.** Два API по 1 CPU/512 MiB, два worker,
LB 128 MiB, RustFS 1 CPU/512 MiB; 3/64 слота × PNG около 1/10 MiB × 10/20/40 клиентов,
три повтора каждой точки. Клиент с macOS, keep-alive, по два upload; перед точкой API/LB
пересоздаются для нового cgroup `memory.peak`. Пик включает процессы, page cache и сокеты;
p95 учитывает только 201. На сохранённом снимке фона — только свой project.
[Методика и 36 raw-точек](evidence/sqlalchemy-2026-11-06/grade4/NOTES.md).
## Ограничения и следующие шаги
| Конфигурация | Ответы в 18 точках | Максимум API | OOM API/LB |
| --- | --- | ---: | ---: |
| 3 слота | 840/840 ×201 | 448,0 MiB | 0 |
| 64 слота, исторический контроль | 813×201, 27×503 | 513,7 MiB | 0 |
- Один Docker-host: RabbitMQ — один узел quorum-очереди без репликации, PostgreSQL и RustFS — единственные точки
отказа; это не HA. Отказы — остановка и `SIGKILL` процессов и контейнеров, не сеть и не диск.
- Это не exactly-once: брокер доставляет повторно (окна 3 и 5, redelivery после рестарта), дубли гасит захват
задания и ключ эффекта. Publisher confirm подтверждает запись в очередь, consumer ack — устойчивый результат.
- Relay держит транзакцию outbox на время публикации пачки; при недоступном брокере он каждую секунду ждёт
таймаут соединения, API это не затрагивает, outbox растёт. LISTEN/NOTIFY не введён: опроса раз в секунду хватает
бюджету smoke.
- Ошибка PostgreSQL на захвате возвращает сообщение в очередь; после 10 возвратов оно уходит в DLQ, а задание
остаётся `queued` с опубликованной строкой outbox. Replay работает только для `failed` (для `queued` — `noop`):
такое сообщение оператор видит `make dlq` и возвращает из DLQ средствами брокера; автоматической
переопубликации «застрявших» `queued` нет.
- Задание, прерванное SIGTERM посреди рендера, вернётся только по истечении аренды (до 60 с): аренда при штатной
остановке не освобождается. Эффекта и дубля нет, только задержка.
- `RLIMIT_AS` применяется только в Linux: в собственных тестах на macOS проверяются таймаут, падение процесса рендера
и `MemoryError`, а сам предел памяти — сценарием `worker_limits` на стенде.
- Replay сбрасывает `attempt` в 1: оператор может повторять неудачную работу сколько угодно раз, каждый раз с записью
`replayed` и именем оператора в журнале.
- `optimized` теряет прозрачность (компоновка на белый, как у остальных вариантов).
- `object_key` лабы 4 в `attachments` оставлен nullable до contract-миграции.
- Нестабильность, найденная прогоном: проверка лабы 2 `test_valkey_restart_keeps_cache_and_revocations` один раз
увидела на 1 ключ меньше после рестарта Valkey (между подсчётами истёк TTL кэшированной сессии); повтор — PASS.
- Подтверждено прогонами: всё в таблице доказательств уровней «3» и «4». Трек 2 — следующее изменение.
**Память F, тоже до PNG-фиксов.** 40 клиентов, по два PNG 10 485 256 байт, 3 слота;
три повтора дали 80/80/78 успешных ответов и 0/0/2 ответа 503. Пики API:
456,2/438,1/450,4 MiB, LB: 31,8/28,5/29,1 MiB, OOM 0; p95 3641,3/4755,0/8091,8 мс.
Причина двух 503 отдельно не локализована; уборка их возможных остатков в этой серии не
измерялась. [Команды, фон и сырьё](evidence/forward-port.md#повтор-затронутых-измерений).
Контроль 64/3 остаётся историческим; новый инспектор измерен отдельно в серии V ниже.
**Память V, после обоих PNG-фиксов.** На том же распределении ресурсов проведены
ровно три новые серии штатных 3 слотов: ~1/10 MiB × 10/20/40 клиентов, два upload на
клиента. Всего **18 точек, 840/840×201**, ошибок/таймаутов/OOM-kill нет.
Максимум API **440,0 MiB / 512 MiB**, LB **31,1 MiB / 128 MiB**.
[Команды, сырьё и фон](evidence/load-validation.md#новая-матрица-памяти),
[пересчёт](evidence/png-final-2026-11-06/memory-summary.json).
| PNG / клиенты | Максимум API из 3 повторов, MiB | p95 успешных: медиана [min–max], мс |
| --- | ---: | ---: |
| ~1 MiB / 10 | 279,8 | 241,0 [134,3–257,7] |
| ~1 MiB / 20 | 284,5 | 243,8 [226,6–310,2] |
| ~1 MiB / 40 | 290,4 | 373,4 [367,6–417,6] |
| ~10 MiB / 10 | 394,8 | 1520,3 [1236,1–3287,8] |
| ~10 MiB / 20 | 440,0 | 2632,8 [2514,0–3632,6] |
| ~10 MiB / 40 | 439,2 | 5971,4 [4256,0–6534,9] |
Дополнительный PNG 8000×5000 RGBA16: 311 100 байт на проводе, 320 005 000 байт
распакованных строк. Перед нагрузкой файл независимо декодирован Pillow. 10 клиентов
стартовали через barrier: **10×201**, 10 побайтных скачиваний вторым участником,
API ≤270,828 MiB, LB ≤24,2 MiB, OOM 0. [Драйвер и raw](evidence/png-final-2026-11-06/high-depth.json).
Это один сильно сжатый паттерн; он не представляет все PNG и не является SLO.
После нагрузок shallow-проверка: 859 ready = 859 объектов, ни pending, ни orphan,
ни missing/size mismatch. SHA всех крупных объектов повторно не вычислялся.
[Сверка](evidence/png-final-2026-11-06/post-memory-invariants.json). На снимках фона —
только свой project; macOS, частоты, диск и кэш физического хоста не контролировались.
**Запись сообщений F.** `make load-evidence`: публичный `tests/load.py`, закрытый контур,
64 клиента, 8 с, новый горячий чат на прогон, три повтора с паузой 15 с. Клиент-контейнер
в edge-сети, 2 CPU/512 MiB; API ×2 по 1 CPU/512 MiB. На снимках до/после — только свой
project, host load average 3,42→4,69. Физический хост не был выделен эксклюзивно.
| Повтор | RPS | p95 успешных, мс | Ошибок |
| --- | ---: | ---: | ---: |
| 1 | 1428,577 | 100,062 | 0 |
| 2 | 1456,338 | 98,948 | 0 |
| 3 | 1529,320 | 98,475 | 0 |
Медиана **1456,338 RPS**, ошибок 0. [Команда](evidence/forward-final-2026-11-06/load-command.txt),
[сырые JSON](evidence/forward-final-2026-11-06/load/), [фон](evidence/forward-final-2026-11-06/performance-before.txt).
Это характеристика данного распределения ресурсов и одного чата, не SLO или предел архитектуры.
Относительно ранней SQLAlchemy-серии 1529,186 RPS разница −4,8%; причинное влияние
исправления из непарных серий не следует. PNG-изменения не вызываются текстовым запросом.
## Трек 2: согласованность двух хранилищ
`make reconcile` запускает `python -m messenger.attachments.entrypoints.reconcile`,
по умолчанию dry-run; `ARGS='--apply --deep'` включает исправления и хеширование.
Один проход сливает листинг S3 и keyset-страницы по `object_key` с индексом UNIQUE/COLLATE C.
Алгоритм делает O(N) сравнений и хранит O(страница); это не обещание линейного времени RustFS.
По умолчанию страница 1000, grace 3600 с + skew 60 с. Advisory lock разрешает один проход;
второй возвращает skipped. Deep хеширует потоками 64 KiB, по умолчанию до восьми объектов.
| Расхождение | Безопасное действие `--apply` |
| --- | --- |
| Старый orphan | Повторная проверка строки по ключу, затем удаление объекта; свежий не трогается |
| Старый pending | Повторная проверка под `FOR UPDATE SKIP LOCKED`, объект раньше строки, audit reason=reconcile |
| Ready без объекта / другой размер / SHA | Повторная проверка; карантин, без удаления ready и ссылок сообщений; `/content` → 404 |
| Объект карантина восстановлен | Снять карантин только после совпадения SHA-256, даже без `--deep` |
**Гипотезы до замеров** — [design на этапе SQLAlchemy](openspec/changes/archive/2026-11-06-verify-lab4-reconciler-sqlalchemy/design.md),
proposal `751aaed4b1baaa957c74bb8874adeb0eac4b0480`:
H1 — точное обнаружение/исправление, повтор 0 и сохранность свежих/используемых;
H2 — shallow t(100k)/t(10k) в [7,13], страницы ceil(N/page), RSS растёт менее чем на 10%,
deep на порядок дороже; H3 — после SQLAlchemy сохраняются страничность и ограниченная память.
Отрицательный результат H2 не меняет исходную гипотезу.
**Корректность F.** На свежем отдельном project, grace 60/skew 0 внедрены ошибки обеих сторон.
Dry-run не изменил 24 объекта/27 строк. Apply удалил 3 старых orphan и 6 pending, перевёл
9 ready в карантин; шесть audit-событий, все шесть ссылок сохранены. Повтор — 0 действий.
Возврат исходных байтов снял один карантин без deep, подмена той же длины — не сняла.
Всего 13 PASS; [первичный demo](evidence/forward-final-2026-11-06/reconcile-demo/demo.json).
При 75 с параллельных upload: 3364×201, 59 проходов, lost_ready=0, независимая проверка SHA
в [check-under-load](evidence/forward-final-2026-11-06/reconcile-demo/check-under-load.json).
**Конкурентная загрузка V после PNG-фиксов:** отдельный fresh project, 75 с / 3 потока,
3341/3341×201, 67 проходов, errors=0/skipped=0, lost_ready=0. Независимый deep-аудит
проверил SHA всех 3341 ready; каждый десятый upload привязан к сообщению. Удалены только
3 внедрённых orphan. [Команда](evidence/png-final-2026-11-06/concurrent-reconcile.txt),
[raw](evidence/png-final-2026-11-06/concurrent-reconcile/under-load.json),
[SHA-аудит](evidence/png-final-2026-11-06/concurrent-reconcile/check-under-load.json).
На пустом dataset инъекция pending создала 0 строк (ей нужна существующая строка-владелец);
этот сценарий повторно не доказан серией V и сохраняется из полного demo F.
Затронутый PNG-путь и сохранность всех 201 проверены; остальной алгоритм не менялся.
Повторную проверку строки перед удалением дополнительно покрывает
`test_row_written_after_listing_keeps_the_object`: наблюдение fresh не подменяет этот барьер.
**Стоимость на `3402fd69d4922e500035a204d957be2cccaeb85a`.** Свежий project
`hlpipe-lab4-cost-20261106`; 1k/10k/30k/100k объектов и столько же ready-строк, PNG 8×8 по 264 B
и один smoke-объект 111 817 B. Наполнение — четыре параллельных PUT и SQLAlchemy batch INSERT;
измерение начинается после COMMIT и тихого окна, время наполнения исключено.
API/LB/Valkey остановлены. RustFS 2 CPU/3 GiB, cpuset 11–12; PG 2 CPU/1 GiB, 13–14;
CLI 1 CPU/256 MiB, 15. Это отдельная конфигурация, не штатные лимиты API-стенда.
Перед каждым повтором фильтр чужого CPU: ≤2 ядра VM и ≤0,25 на закреплённых,
запас запуска 1,5/0,5 ядро·с; quiet 15 с, deadline 900 с, до трёх повторов отклонённой точки.
Приняты 27, отклонённых 0; максимум чужого CPU 0,25 ядра, pinned 0. По три shallow/deep
на каждом N и три page100 на 10k. Все raw с исходным SHA сохранены и пересчитаны при отчёте.
[Команда](evidence/sqlalchemy-2026-11-06/track5/cost-command.txt),
[полный протокол](evidence/sqlalchemy-2026-11-06/track5/NOTES.md),
[план/фон/сырьё](evidence/sqlalchemy-2026-11-06/track5/measurements/cost/).
| N | Режим | Медиана прохода [min–max], с | LIST / SQL-страниц / GET | RSS, MiB, медиана |
| ---: | --- | --- | --- | ---: |
| 1000 | shallow | 0,107 [0,105–0,113] | 1 / 1 / 0 | 109,8 |
| 1000 | deep | 0,499 [0,498–0,536] | 1 / 1 / 1000 | 110,2 |
| 10000 | shallow | 0,999 [0,996–1,077] | 10 / 10 / 0 | 110,9 |
| 10000 | deep | 4,998 [4,972–5,041] | 10 / 10 / 10000 | 111,3 |
| 10000 | page100 | 2,037 [2,035–2,113] | 100 / 100 / 0 | 107,9 |
| 30000 | shallow | 3,601 [3,567–3,633] | 30 / 30 / 0 | 110,9 |
| 30000 | deep | 15,665 [15,630–15,779] | 30 / 30 / 30000 | 111,6 |
| 100000 | shallow | 20,215 [20,206–21,335] | 100 / 100 / 0 | 111,1 |
| 100000 | deep | 110,910 [58,661–147,215] | 100 / 100 / 100000 | 111,4 |
SQL здесь считает запросы страниц, без служебных BEGIN/COMMIT/pre-ping/advisory lock;
HEAD/DELETE=0 во всех точках. `cost.seconds` — сам проход, CPU/wall в raw включают старт CLI.
**H2 о времени отвергнута:** t100k/t10k=20,235. На 100k листинг занимает медиану 19,538 с;
внутренняя причина его удорожания не установлена. Deep дороже в 4,35–5,49 раза, не на порядок.
Страницы точно ceil(N/page), shallow RSS 109,8→111,1 MiB (+1,18%): эти части H2 и H3
подтверждены в измеренной области. H1 подтверждена перечисленными сценариями на F.
Deep 100k: 147,215/110,910/58,661 с, разброс 79,84% медианы. Все повторы прошли заранее
заданный фильтр; лучший не выбран вместо остальных. Один хост/VM, тёплые данные, частоты,
диск и нагрузка macOS не контролировались. PNG 264 B не прогнозируют deep для 10 MiB,
выше 100k измерений нет. Сравнение с историческим asyncpg — не причинный A/B-эксперимент.
Сверка не восстанавливает утраченные байты и требует отдельного ручного/планового запуска.
## Завершение финальной validation
[Общий долг двух PNG-фиксов](evidence/png-header-fix/NOTES.md#обязательные-проверки-финального-этапа)
закрыт на V: API-тесты с PostgreSQL, upload faults через LB/RustFS, 18 точек штатной
матрицы RAM, десять одновременных 40 MP RGBA16 и upload при сверке с независимым SHA-аудитом.
Команды и сырые результаты — в [аудите](evidence/load-validation.md).
`make student-test` дал 719 PASS и 2 setup errors из-за неготового временного RustFS;
адресный повтор только этих двух тестов прошёл. Таким образом, все 721 выбранная
проверка исполнена успешно, первый полный запуск не объявляется зелёным. Отдельно
7 stack-тестов PASS. `make check`, `make validate`, `make lint` и OpenSpec strict (18)
прошли. Реализация, конфиги, нормативные файлы и OpenSpec не менялись.
Принятые 27 cost-замеров и 3 повтора текстовой нагрузки сохранены с исходными SHA: повтор
не требовался. Старые 64/3 и upload-memory до PNG-фиксов не используются для вывода о
новом инспекторе. После Docker-этапа оба собственных project остановлены, шесть постоянных
volumes сохранены; [инвентаризация](evidence/png-final-2026-11-06/shutdown-state.txt).
Публикация — только после отдельной команды координатора PUBLICATION; push не выполнялся.
## Ограничения
- **Minor, сохранён ревью:** непарные Unicode-суррогаты U+D800/U+DFFF в `text` вызывают
`PydanticSerializationError` в `fingerprint()` и HTTP 500. Файл
[schemas.py:35](src/messenger/messaging/entrypoints/schemas.py#L35),
[HTTP-доказательство](evidence/forward-final-2026-11-06/known-minor-http.txt).
Это дефект, не PASS; по правилу пользователя minor не требует fix и не блокирует этап.
- Один Docker-host, по одному PostgreSQL/RustFS/LB — точки отказа; репликация и резервные
копии байтов здесь не исследуются. При остановке всех API sweeper ждёт их возврата.
- Тело upload ограничено, но хранится целиком; слоты защищают память ценой очереди.
Два 503 в F сохранены без объяснения недоказанной причиной. В V все 840 запросов
успешны при пике ≤440 MiB; это измеренная область 10–40 клиентов, не общий предел RAM
и не обещание 100% успеха при любой нагрузке.
- При неизвестном результате PUT/COMMIT остаток ждёт grace; потерянный ответ upload
допускает повторное вложение, поскольку у этого endpoint нет Idempotency-Key.
- После отправки заголовков сбой S3 при download может оборвать поток; слишком медленная
передача и SIGTERM также ограничены таймаутами. Ранний отказ во время отправки большого
тела клиент иногда увидит как reset. Сессия проверяется раньше объявленного размера.
- В demo grace 60/skew 0, смещение часов не моделировалось; реальный grace API 900 с
отдельно подтверждён старой серией S. Reconciler не восстанавливает повреждённые байты.
- Нагрузка записи — закрытый контур и один чат, успешные latency имеют coordinated omission.
Причинный эффект SQLAlchemy/исправлений и предел системы из этих чисел не выводятся.
- Секреты — локальные файлы Compose вместо менеджера секретов; статические S3-ключи без
исследованной ротации. TLS, presigned flow, брокер и варианты изображений вне этой лабы.
- Исторические proposal `add-lab4-image-attachments` и `add-lab4-upload-resilience`
превышают рекомендацию 400 слов; история не переписана. `openspec/config.yaml` сверён
с текущим стеком, но в документационном этапе не редактировался по ограничению области работ.
## Ответы на вопросы защиты
**Почему volume одной API-реплики не равен объектному хранилищу?** Другая реплика не обязана
видеть её локальный volume. RustFS даёт всем репликам одно адресуемое ключами хранилище
с политиками доступа; остановка принявшей API не удаляет оригинал. В F это показали
разные `X-Instance-Id` и совпавший SHA-256 после остановки target.
**Когда можно вернуть 201?** После успешного PUT и COMMIT статуса ready. Pending уже
зафиксирован до PUT, но не виден пользователям. Потерянный ответ после COMMIT возможен;
это не позволяет заранее отвечать 201.
**Что если S3 PUT прошёл, а COMMIT — нет?** При известном отказе компенсация под блокировкой
удаляет объект, затем pending. При падении процесса/неизвестном исходе это делает sweeper
после grace. Уже ready не удаляется; независимые orphan и расхождения ищет reconciler.
**Почему случайный key/private bucket не заменяют ACL?** S3-ключ API разрешает доступ
ко всему bucket и не знает членства пользователей в чатах. Поэтому каждый запрос
метаданных/байтов проверяет членство; постороннему 404. Private bucket дополнительно
закрывает прямой анонимный GET, но не принимает решение за приложение.
Для защиты: `make test` показывает upload→message→download и чужому 404;
`make s3-check` — private вне API; persistence/failover — сохранность;
`make attachments-evidence` — отсутствие локальных файлов API; сценарии уровней 4/5 —
компенсацию, ограничения памяти и безопасную сверку. Следует показать исходный SHA каждого
результата и новые доказательства PNG-инспектора из серии V.
Решение перенесено из собственной ЛР3. При реализации и подготовке отчёта использован Codex;
автор работы — Костылев Артём. Нормативные README/COURSE/contracts/tests сохранены.
+1 -11
View File
@@ -6,13 +6,7 @@ from legacy import adopt_legacy
from sqlalchemy import Connection, func, make_url, pool, select
from sqlalchemy.ext.asyncio import create_async_engine
from messenger.attachments.infrastructure.postgres import (
AttachmentRow,
JobEventRow,
JobRow,
OutboxRow,
VariantRow,
)
from messenger.attachments.infrastructure.postgres import AttachmentRow
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
from messenger.messaging.infrastructure.postgres import (
ChatMemberRow,
@@ -32,10 +26,6 @@ MODELS = (
MessageRow,
IdempotencyKeyRow,
AttachmentRow,
JobRow,
OutboxRow,
JobEventRow,
VariantRow,
MessageAttachmentRow,
)
target_metadata = UserRow.metadata
+1 -3
View File
@@ -10,9 +10,7 @@ LEGACY = {
"0001_init": "9a13618f078ae9056431391e2e5197a31b981ae1fff047a9b3421ac750d3fd0d",
"0002_idempotency_keys": "d9159a35553249a1e51af5f2e4e7c39b014e97593c49748e13f3799839063dd0",
"0003_attachments": "c4417f560538a083efba1c67f660147dc94532fcbb2fa91f3f3e8258a0f01f2e",
"0004_jobs": "c3887fa7a886ae8153a216aa43fd4c3c6190a2074e8ce20c3e77f29bfb01550e",
"0005_failed_registry": "02b80061a08a6929feb092148c453ad970e3d001901c651b5a73b90b1e40f145",
"0006_attachment_quarantine": (
"0004_attachment_quarantine": (
"541f5399d87fac3584c4102b4e0bf92c23cd372cc20a7d56dad03e771773202c"
),
}
@@ -1,8 +1,8 @@
import sqlalchemy as sa
from alembic import op
revision = "0006_attachment_quarantine"
down_revision = "0005_failed_registry"
revision = "0004_attachment_quarantine"
down_revision = "0003_attachments"
branch_labels = None
depends_on = None
-146
View File
@@ -1,146 +0,0 @@
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "0004_jobs"
down_revision = "0003_attachments"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.drop_constraint("attachments_status_check", "attachments", type_="check")
op.create_check_constraint(
"attachments_status_check",
"attachments",
"status IN ('pending', 'queued', 'processing', 'ready', 'failed')",
)
for name in ("staging_key", "original_key"):
op.add_column("attachments", sa.Column(name, sa.Text(collation="C"), nullable=True))
op.create_unique_constraint(f"attachments_{name}_key", "attachments", [name])
op.add_column(
"attachments",
sa.Column("published_version", sa.Integer(), nullable=False, server_default="0"),
)
op.create_check_constraint(
"attachments_published_version_check", "attachments", "published_version >= 0"
)
op.add_column("attachments", sa.Column("error_code", sa.Text(), nullable=True))
op.create_check_constraint(
"attachments_error_code_check",
"attachments",
"error_code IN ('invalid_image', 'processing_failed', 'retry_exhausted')",
)
op.alter_column("attachments", "object_key", nullable=True)
attachments = sa.table(
"attachments",
sa.column("status"),
sa.column("object_key"),
sa.column("original_key"),
sa.column("staging_key"),
sa.column("published_version"),
)
op.execute(
attachments.update()
.where(attachments.c.status == "ready")
.values(original_key=attachments.c.object_key, published_version=1)
)
op.execute(
attachments.update()
.where(attachments.c.status == "pending")
.values(staging_key=attachments.c.object_key)
)
op.create_index(
"attachments_staged_idx",
"attachments",
["updated_at"],
postgresql_where=sa.column("staging_key").is_not(None),
)
op.create_table(
"attachment_variants",
sa.Column("attachment_id", sa.Uuid(), sa.ForeignKey("attachments.id"), nullable=False),
sa.Column("pipeline_version", sa.Integer(), nullable=False),
sa.Column("name", sa.Text(), nullable=False),
sa.Column("object_key", sa.Text(collation="C"), nullable=False),
sa.Column("content_type", sa.Text(), nullable=False),
sa.Column("size_bytes", sa.BigInteger(), nullable=False),
sa.Column("width", sa.Integer(), nullable=False),
sa.Column("height", sa.Integer(), nullable=False),
sa.Column("sha256", sa.Text(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("attachment_id", "pipeline_version", "name"),
sa.UniqueConstraint("object_key", name="attachment_variants_object_key_key"),
sa.CheckConstraint(
"pipeline_version >= 1", name="attachment_variants_pipeline_version_check"
),
sa.CheckConstraint(
"name IN ('thumbnail', 'crop', 'optimized')", name="attachment_variants_name_check"
),
sa.CheckConstraint(
"content_type IN ('image/jpeg', 'image/png', 'image/webp')",
name="attachment_variants_content_type_check",
),
sa.CheckConstraint("size_bytes >= 1", name="attachment_variants_size_bytes_check"),
sa.CheckConstraint("width >= 1", name="attachment_variants_width_check"),
sa.CheckConstraint("height >= 1", name="attachment_variants_height_check"),
sa.CheckConstraint("sha256 ~ '^[0-9a-f]{64}$'", name="attachment_variants_sha256_check"),
)
op.create_table(
"jobs",
sa.Column("job_id", sa.Uuid(), primary_key=True),
sa.Column("attachment_id", sa.Uuid(), sa.ForeignKey("attachments.id"), nullable=False),
sa.Column("pipeline_version", sa.Integer(), nullable=False),
sa.Column("status", sa.Text(), nullable=False),
sa.Column("attempt", sa.Integer(), nullable=False),
sa.Column("claims", sa.Integer(), nullable=False, server_default="0"),
sa.Column("lease_token", sa.Uuid(), nullable=True),
sa.Column("lease_until", sa.DateTime(timezone=True), nullable=True),
sa.Column("next_attempt_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_error", sa.Text(), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.UniqueConstraint("attachment_id", "pipeline_version", name="jobs_effect_key"),
sa.CheckConstraint("pipeline_version >= 1", name="jobs_pipeline_version_check"),
sa.CheckConstraint(
"status IN ('queued', 'processing', 'done', 'failed', 'superseded')",
name="jobs_status_check",
),
sa.CheckConstraint("attempt >= 1", name="jobs_attempt_check"),
sa.CheckConstraint("claims >= 0", name="jobs_claims_check"),
)
op.create_index(
"jobs_lease_idx",
"jobs",
["lease_until"],
postgresql_where=sa.column("status") == "processing",
)
op.create_table(
"outbox",
sa.Column("id", sa.BigInteger(), sa.Identity(always=True), primary_key=True),
sa.Column("job_id", sa.Uuid(), sa.ForeignKey("jobs.job_id"), nullable=False),
sa.Column("payload", postgresql.JSONB(), nullable=False),
sa.Column("available_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("published_at", sa.DateTime(timezone=True), nullable=True),
)
op.create_index(
"outbox_pending_idx",
"outbox",
["available_at", "id"],
postgresql_where=sa.column("published_at").is_(None),
)
op.create_index("outbox_job_idx", "outbox", ["job_id"])
op.create_table(
"job_events",
sa.Column("id", sa.BigInteger(), sa.Identity(always=True), primary_key=True),
sa.Column("job_id", sa.Uuid(), nullable=False),
sa.Column("attachment_id", sa.Uuid(), nullable=False),
sa.Column("kind", sa.Text(), nullable=False),
sa.Column("attempt", sa.Integer(), nullable=True),
sa.Column("detail", postgresql.JSONB(), nullable=False, server_default="{}"),
sa.Column("at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
)
op.create_index("job_events_attachment_idx", "job_events", ["attachment_id", "id"])
def downgrade() -> None:
raise RuntimeError("Downgrade would delete pipeline data")
-20
View File
@@ -1,20 +0,0 @@
import sqlalchemy as sa
from alembic import op
revision = "0005_failed_registry"
down_revision = "0004_jobs"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_index(
"jobs_failed_idx",
"jobs",
[sa.column("updated_at").desc()],
postgresql_where=sa.column("status") == "failed",
)
def downgrade() -> None:
op.drop_index("jobs_failed_idx", table_name="jobs")
+1 -3
View File
@@ -1,14 +1,12 @@
# Topology worksheet, deliberately NOT a runnable stack (no application supplied).
# Implement compose.yaml or stack.yaml; do not submit this empty file as deployment.
# Service names below are logical roles, not imposed container names.
x-lab-number: 5
x-lab-number: 4
x-required-roles:
- api
- postgres
- load_balancer
- s3
- broker
- worker
# TODO: implement real images/builds, network wiring, volumes, healthchecks,
# credentials and bootstrap. Details: contracts/infrastructure.json and README.md.
services: {}
+2 -126
View File
@@ -18,44 +18,6 @@ x-s3-env: &s3-env
UPLOAD_SWEEP_INTERVAL_SECONDS: ${UPLOAD_SWEEP_INTERVAL_SECONDS:-30}
UPLOAD_SWEEP_BATCH: ${UPLOAD_SWEEP_BATCH:-100}
x-pipeline: &pipeline
image: ${API_IMAGE:-mtusi-messenger:${COMPOSE_PROJECT_NAME}}
pull_policy: never
restart: unless-stopped
init: true
read_only: true
tmpfs: [/tmp]
security_opt: ["no-new-privileges:true"]
cap_drop: [ALL]
stop_grace_period: 10s
networks: [backend]
healthcheck:
test: ["CMD", "python", "-c", "import os,sys,time;sys.exit(time.time()-os.stat('/tmp/heartbeat').st_mtime>30)"]
interval: 10s
timeout: 5s
retries: 3
start_period: 30s
start_interval: 2s
depends_on:
migrate:
condition: service_completed_successfully
s3-init:
condition: service_completed_successfully
broker:
condition: service_healthy
x-pipeline-env: &pipeline-env
<<: *s3-env
DATABASE_URL_FILE: /run/secrets/database_url
BROKER_URL_FILE: /run/secrets/broker_url
DB_POOL_MAX_SIZE: ${PIPELINE_DB_POOL_MAX_SIZE:-4}
LOG_LEVEL: ${LOG_LEVEL:-INFO}
HEARTBEAT_FILE: /tmp/heartbeat
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
JOB_BACKOFF_BASE_SECONDS: ${JOB_BACKOFF_BASE_SECONDS:-2}
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
x-s3-client: &s3-client
image: rustfs/rc:v0.1.36@sha256:ab024bfebee49a750ce886b4c70963ccd9ddaa03f491704a90710641d7a26699
read_only: true
@@ -73,8 +35,6 @@ x-s3-client: &s3-client
- s3_secret_access_key
- s3_reconciler_access_key_id
- s3_reconciler_secret_access_key
- s3_worker_access_key_id
- s3_worker_secret_access_key
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
restart: "no"
@@ -90,8 +50,8 @@ services:
API_SERVER_MAXCONN: ${API_SERVER_MAXCONN:-64}
volumes: [./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro]
ports:
- "127.0.0.1:${LB_HTTP_PORT:-18085}:8080"
- "127.0.0.1:${LB_STATS_PORT:-25085}:8404"
- "127.0.0.1:${LB_HTTP_PORT:-8080}:8080"
- "127.0.0.1:${LB_STATS_PORT:-8404}:8404"
networks: [edge, backend]
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/healthz"]
@@ -316,77 +276,6 @@ services:
profiles: [tools]
entrypoint: ["/bin/sh", "/s3/cli.sh"]
broker:
image: rabbitmq:4.1.8-management-alpine@sha256:54ef5ff505352c1beef05a97ee9bd6ab95b3559a76629ba0119b1d63d8d6e4b2
hostname: broker
user: "100:101"
restart: unless-stopped
read_only: true
tmpfs: [/tmp]
security_opt: ["no-new-privileges:true"]
cap_drop: [ALL]
ports:
- "127.0.0.1:${BROKER_MANAGEMENT_PORT:-25086}:15672"
networks: [backend, edge]
volumes:
- broker-data:/var/lib/rabbitmq
- ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/conf.d/20-messenger.conf:ro
- ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro
- ./infra/rabbitmq/definitions.json:/etc/rabbitmq/definitions.d/10-topology.json:ro
secrets:
- source: rabbitmq_users
target: /etc/rabbitmq/definitions.d/20-users.json
- rabbitmq_ops_password
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"]
interval: 10s
timeout: 10s
retries: 5
start_period: 60s
start_interval: 2s
stop_grace_period: 10s
deploy:
resources:
limits: {cpus: "1", memory: 512m}
relay:
<<: *pipeline
command: ["python", "-m", "messenger.relay"]
environment:
<<: *pipeline-env
OUTBOX_POLL_SECONDS: ${OUTBOX_POLL_SECONDS:-1}
SWEEP_INTERVAL_SECONDS: ${SWEEP_INTERVAL_SECONDS:-5}
secrets:
- database_url
- source: broker_url_api
target: broker_url
- s3_access_key_id
- s3_secret_access_key
deploy:
resources:
limits: {cpus: "0.5", memory: 192m}
worker:
<<: *pipeline
command: ["python", "-m", "messenger.worker"]
environment:
<<: *pipeline-env
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
RENDER_TIMEOUT_SECONDS: ${RENDER_TIMEOUT_SECONDS:-30}
RENDER_MEMORY_MB: ${RENDER_MEMORY_MB:-448}
RENDER_TASKS_PER_CHILD: ${RENDER_TASKS_PER_CHILD:-100}
secrets:
- database_url
- source: broker_url_worker
target: broker_url
- source: s3_worker_access_key_id
target: s3_access_key_id
- source: s3_worker_secret_access_key
target: s3_secret_access_key
deploy:
resources:
limits: {cpus: "${WORKER_CPUS:-2}", memory: "${WORKER_MEMORY:-1g}"}
k6:
image: grafana/k6:2.3.0@sha256:2dd4756ec6e14e62778916e1eb850108e4b499304c02df56760fa0bdb0fba0b8
profiles: [bench]
@@ -417,18 +306,6 @@ secrets:
file: ./secrets/s3_access_key_id
s3_secret_access_key:
file: ./secrets/s3_secret_access_key
s3_worker_access_key_id:
file: ./secrets/s3_worker_access_key_id
s3_worker_secret_access_key:
file: ./secrets/s3_worker_secret_access_key
rabbitmq_users:
file: ./secrets/rabbitmq_users.json
rabbitmq_ops_password:
file: ./secrets/rabbitmq_ops_password
broker_url_api:
file: ./secrets/broker_url_api
broker_url_worker:
file: ./secrets/broker_url_worker
s3_reconciler_access_key_id:
file: ./secrets/s3_reconciler_access_key_id
s3_reconciler_secret_access_key:
@@ -438,7 +315,6 @@ volumes:
pgdata:
valkeydata:
s3data:
broker-data:
networks:
edge:
-21
View File
@@ -1,21 +0,0 @@
# Состояния вложения и договор между producer/worker
Сообщение broker соответствует [jobs.schema.json](jobs.schema.json). Можно применять native headers брокера для trace context, но семантика carrier сохраняется; для проверки покажите отображение полей. `job_id` идентифицирует одну логическую работу и не меняется при redelivery; `attempt` начинается с 1 и отражает управляемую попытку обработки (broker redelivery сам по себе не создаёт новый job_id). Ключ эффекта — `(attachment_id, pipeline_version, variant)`.
| Переход | Условие | Что устойчиво сохранено |
| --- | --- | --- |
| нет → queued | Принимаем upload; только после durable handoff отвечаем 202 | Полный проверенный оригинал в staging, метаданные, намерение обработки |
| queued → processing | Worker захватил/арендовал работу | Попытка, lease/deadline или эквивалентная защита |
| processing → queued | Временная ошибка и остались попытки | Причина без секретов, время следующей попытки |
| processing → ready | Все обязательные объекты записаны и результат атомарно опубликован | Оригинал, thumbnail (на 4 ещё crop/optimized), метаданные/checksums |
| processing → failed | Ошибка постоянная или попытки исчерпаны | error_code и запись, доступная оператору |
| processing → queued | Истёк lease после смерти worker | Восстановленная работа, без дублирования эффектов |
| failed → queued | Явный операторский replay, доступен на 4 | Audit, новая попытка, прежний логический эффект защищён от дубля |
Повторная доставка уже ready-задачи — no-op с ack после проверки завершённого эффекта. Конкурентные попытки не перезаписывают более новый pipeline_version. Основной курс использует pipeline_version=1; версионирование нескольких pipeline — трек 5. Заявляйте готовность только когда все обещанные уровнем варианты доступны. Нельзя откатывать ready в processing из-за старого дубля.
**Окна отказа для защиты:** после staging до записи задания; после COMMIT до publish; после publish до confirm; после записи S3 до COMMIT результата; после COMMIT результата до ack. На 3 покажите сохранность успешно принятой работы и повторную доставку; на 4 автоматическое восстановление разрыва DB/broker (outbox/эквивалент) и зависшего processing.
Staging не удаляется до безопасной публикации результатов. Неуспешные/непривязанные исходники имеют документированный retention и cleanup; он не удаляет текущую работу. Broker принимает только ID/служебные данные, не произвольный URL для скачивания и не путь из клиентского filename. Worker берёт доверенные storage metadata из БД.
Ack подтверждает устойчивую обработку, publisher confirm — приём брокером; это разные границы. См. [RabbitMQ reliability](https://www.rabbitmq.com/docs/reliability). At-least-once + идемпотентный эффект не означает exactly-once доставку.
+1 -17
View File
@@ -1,5 +1,5 @@
{
"lab": 5,
"lab": 4,
"kind": "requirements, not runnable deployment",
"required_for_grade_3": [
{
@@ -27,22 +27,6 @@
],
"private_bucket": true,
"persistent_volume": true
},
{
"role": "broker",
"choose_one": [
"RabbitMQ",
"Redis Streams",
"Valkey Streams",
"NATS JetStream",
"documented durable equivalent"
],
"persistent_volume": true,
"delivery": "at-least-once"
},
{
"role": "worker",
"separate_process": true
}
],
"optional_components": [
-63
View File
@@ -1,63 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:mtusi:messenger:attachment-job:v1",
"title": "Durable attachment processing job v1",
"type": "object",
"additionalProperties": false,
"required": [
"schema_version",
"job_id",
"type",
"attachment_id",
"pipeline_version",
"attempt",
"created_at"
],
"properties": {
"schema_version": {
"const": 1
},
"job_id": {
"type": "string",
"format": "uuid"
},
"type": {
"const": "attachment.process.v1"
},
"attachment_id": {
"type": "string",
"format": "uuid"
},
"pipeline_version": {
"type": "integer",
"minimum": 1
},
"attempt": {
"type": "integer",
"minimum": 1
},
"created_at": {
"type": "string",
"format": "date-time"
},
"traceparent": {
"type": "string",
"pattern": "^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$"
},
"tracestate": {
"type": "string",
"maxLength": 512
}
},
"examples": [
{
"schema_version": 1,
"job_id": "11111111-1111-4111-8111-111111111111",
"type": "attachment.process.v1",
"attachment_id": "22222222-2222-4222-8222-222222222222",
"pipeline_version": 1,
"attempt": 1,
"created_at": "2026-09-01T12:00:00Z"
}
]
}
+5 -11
View File
@@ -1,8 +1,8 @@
{
"openapi": "3.1.0",
"info": {
"title": "MTUSI Messenger — лабораторная 5",
"version": "1.5.0",
"title": "MTUSI Messenger — лабораторная 4",
"version": "1.4.0",
"description": "Нормативный минимум на 3. Семантика: contracts/README.md. Расширения на 4/5 не должны менять этот API. Наличие кода ошибки в схеме не требует реализовать факультативную причину его выдачи."
},
"servers": [
@@ -2151,7 +2151,7 @@
"operationId": "uploadAttachment",
"summary": "Принять один PNG/JPEG, до 10 MiB",
"responses": {
"202": {
"201": {
"description": "Успех",
"headers": {
"X-Request-Id": {
@@ -2936,10 +2936,7 @@
"schema": {
"type": "string",
"enum": [
"original",
"thumbnail",
"crop",
"optimized"
"original"
],
"default": "original"
}
@@ -3464,10 +3461,7 @@
"status": {
"type": "string",
"enum": [
"queued",
"processing",
"ready",
"failed"
"ready"
]
},
"variants": {
+110 -3
View File
@@ -1,5 +1,112 @@
# Доказательства
# Индекс доказательств ЛР4
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
Финальный validation snapshot: `5e49502ae78fa48b992c97418e490666c699726d`, 2026-11-06.
Runtime совпадает с review `7a0ebac2aa9e1d8602054ca4c7c1b0c23d3bfad4`;
[аудит применимости и новые проверки](load-validation.md). Сохранённые cost и текстовая
нагрузка приняты с исходными SHA. Старые upload-memory остаются историческими.
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
## Финальная validation после PNG-фиксов
| Команда / назначение | Наблюдение | Файл |
| --- | --- | --- |
| `make student-test PYTEST_ARGS='-q --tb=short'`, затем адресный повтор двух S3-тестов | 719 PASS + 2 setup errors RustFS; только эти два повторены: 2 PASS. 721 выбранная проверка исполнена; первый запуск не объявлен зелёным | [полный](png-final-2026-11-06/student-test.txt), [повтор](png-final-2026-11-06/student-s3-retry.txt) |
| `make up`, `make test`, `scripts/limits.py` | Новый изолированный project, fresh volumes, штатные лимиты, smoke PASS | [up](png-final-2026-11-06/up.txt), [smoke](png-final-2026-11-06/smoke.txt), [лимиты](png-final-2026-11-06/limits.txt) |
| Прямой argv `make upload-faults`, новый путь захвата | 7 PASS; оба PNG → 415; негативный suite: 0×5xx | [raw](png-final-2026-11-06/upload-faults.txt) |
| `png-roundtrip.py` | 415 без новых строк/объектов; PNG/JPEG → 201 и побайтное скачивание | [raw](png-final-2026-11-06/png-roundtrip.json) |
| `make upload-memory ARGS='--slots 3 --out <новый-runN>'`, 3 серии | 18 точек, 840/840×201, API ≤440 MiB, LB ≤31,1 MiB, OOM 0 | [сводка](png-final-2026-11-06/memory-summary.json), [raw](png-final-2026-11-06/upload-memory/) |
| `high-depth.py` | 10 параллельных 40 MP RGBA16, 10×201, checksum совпал, API ≤270,828 MiB, OOM 0 | [raw](png-final-2026-11-06/high-depth.json) |
| `scripts/reconcile_check.py` после RAM | 859 ready = 859 объектов, расхождений/остатков нет; shallow | [raw](png-final-2026-11-06/post-memory-invariants.json) |
| `concurrent-reconcile.py` (только under_load) | 3341×201, 67 проходов, 3 orphan удалены; deep SHA/lost_ready=0. Pending инъекция 0 на пустом dataset, прежний сценарий F сохранён | [raw](png-final-2026-11-06/concurrent-reconcile/under-load.json), [oracle](png-final-2026-11-06/concurrent-reconcile/check-under-load.json) |
| Повторный аудит 27 cost-замеров | Приняты все 27; страницы/память подтверждены, линейность времени отвергнута | [аудит](png-final-2026-11-06/cost-reaudit.json), [diff/SHA](png-final-2026-11-06/retained-audit.json) |
## Offline-проверки до финальной validation
| Команда / назначение | Результат | SHA и файлы |
| --- | --- | --- |
| `make student-test PYTEST_ARGS='-q --tb=short student-tests/unit'` | 407 passed; оба повреждённых PNG отклоняются до записи | Код `7c8a1a64899dc0a1b5fa0949c0992ef40722eacf`; [unit](png-header-fix/unit.txt), [227 проверок инспектора/ASGI](png-header-fix/targeted.txt), [blob-манифест](png-header-fix/manifest.json) |
| `make check`, `make validate`, `make lint`, `openspec validate --all --strict --no-interactive` после фикса | PASS, 18 спецификаций после архивации | Архив `7a0ebac2aa9e1d8602054ca4c7c1b0c23d3bfad4`; [протокол](png-header-fix/NOTES.md), [OpenSpec](png-header-fix/openspec-final.txt) |
| Статическое/offline-ревью runner, round3 | Открытых major нет, один minor; Docker/нагрузки не выполнялись | Результат передан runner для `7a0ebac2aa9e1d8602054ca4c7c1b0c23d3bfad4`; отдельного raw-файла ревью в репозитории нет |
| Документационный аудит: check/validate/lint/OpenSpec, числа, ссылки, diff | Проверки отчётного этапа отдельно от предыдущих тестов | [Аудит](report-audit-2026-11-06.md); исходный snapshot указан выше |
| Финальные API/LB/RustFS-регрессии, память нового инспектора и upload при сверке | Выполненные результаты финальной фазы вынесены выше и в аудит применимости | [Общий долг двух PNG-фиксов](png-header-fix/NOTES.md#обязательные-проверки-финального-этапа) |
Первый PNG-фикс: `9387c3d82ab77ea376eecce19a36a22803d35efb`,
[причина и offline-доказательства](png-validation-fix/NOTES.md).
Второй фикс требует единственный IHDR; вместе они добавляют распаковку PNG ограниченными
блоками. Все предыдущие upload-memory и конкурентные upload в исторических разделах ниже
относятся к старому инспектору. Collection API/stack в `png-header-fix/` — сбор тестов, не их исполнение.
## После позднего переноса ЛР3, до PNG-фиксов
Runtime SHA **F**: `75b93bbba5f29575d3fca1d013cc7e0770d88082`, архив
`8bc2da2c094afc7e5f5e97c7beb5f278e76253fd`. Источник — immutable snapshot ЛР3
`ba78cf6da439a4ec60fd59389583b38285b0b2b1`, диапазон от `f591fa64e525679a31c9db7f942d36c789e1a12f`.
[Все 214 путей и область применимости](forward-port.md), [source-manifest](forward-final-2026-11-06/source-manifest.json).
Все успешные команды таблицы — на F; их полный argv, UTC, разрешённое окружение и exit code
находятся в raw. Пользователи, данные и файлы синтетические.
| Проверка / команда | Наблюдение | Файл |
| --- | --- | --- |
| `make check`, `make validate`, `make lint`, `make student-test` | PASS, 492 теста / 19 stack deselected | [offline-checks-rerun](forward-final-2026-11-06/offline-checks-rerun.txt) |
| `make up`, `make test` | Обе реплики healthy; smoke/checksum/ACL PASS | [up](forward-final-2026-11-06/up.txt), [smoke](forward-final-2026-11-06/smoke.txt), [после нагрузок](forward-final-2026-11-06/final-smoke.txt) |
| `sh scripts/persistence-evidence.sh http://127.0.0.1:18084` | PASS; StartedAt API/LB/PG/Valkey/S3 изменились | [persistence-rerun](forward-final-2026-11-06/persistence-rerun.txt) |
| `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | Target exited; 130 записей, 0 ошибок, 2,883 с до первой записи | [команда](forward-final-2026-11-06/failover-command.txt), [вывод/inspect](forward-final-2026-11-06/failover-d4c8d53d7433.txt) |
| `make scenario SCENARIO=failover-upload`; отдельный `make restore` | Другая реплика отдала те же байты; восстановление выполнено отдельно | [команда](forward-final-2026-11-06/failover-upload-command.txt), [JSON](forward-final-2026-11-06/failover-upload.json), [restore](forward-final-2026-11-06/restore.txt) |
| `make scenario SCENARIO=s3-outage` | 503 за 4,990/5,329 с; текст 201; checksum после старта совпал | [команда](forward-final-2026-11-06/s3-outage-command.txt), [JSON](forward-final-2026-11-06/s3-outage.json) |
| `make test-faults` | 19 PASS, 112 ответов негативной файловой проверки без 5xx; компенсация/crash/grace/stall/PG/Valkey | [stack-faults](forward-final-2026-11-06/stack-faults.txt) |
| `student-tests/tools/forward_network.py`; HAProxy fixture | Сессии/NUL/Basic PASS; 12 проверок реальных 502/503/504 и request_id | [сеть](forward-final-2026-11-06/network-regressions.txt), [LB](forward-final-2026-11-06/haproxy-errors.txt) |
| `make limits` | Ресурсы, порты, mounts, сети и роли секретов PASS | [limits](forward-final-2026-11-06/limits.txt) |
| `make load-evidence` | 3 повтора, медиана 1456,338 RPS, 0 ошибок; текстовый путь не менялся | [команда](forward-final-2026-11-06/load-command.txt), [вывод](forward-final-2026-11-06/load.txt), [raw JSON](forward-final-2026-11-06/load/) |
| `scripts/upload_memory.py --slots 3 --sizes 10485760 --levels 40 --out ...` | 3×80: 238×201, 2×503; пик API 456,2 MiB, OOM 0. Историческая память до PNG-фиксов | [run1](forward-final-2026-11-06/memory-1.txt), [run2](forward-final-2026-11-06/memory-2.txt), [run3](forward-final-2026-11-06/memory-3.txt), [raw](forward-final-2026-11-06/memory/) |
| `make reconcile-demo ARGS='--out evidence/forward-final-2026-11-06/reconcile-demo'` | 13 PASS; 3364 upload, 59 проходов, lost_ready 0. Конкурентные upload требуют повторения после PNG-фиксов | [команда](forward-final-2026-11-06/reconcile-demo.txt), [demo](forward-final-2026-11-06/reconcile-demo/demo.json), [deep-аудит](forward-final-2026-11-06/reconcile-demo/check-under-load.json) |
| `git diff --exit-code` измеряемых файлов | Стоимость reconciler сохранена с исходным SHA, не переснята на F | [retained-cost-audit](forward-final-2026-11-06/retained-cost-audit.txt) |
| Воспроизведение непарных surrogate в text | Два HTTP 500: известный **minor**, не успешный тест | [HTTP](forward-final-2026-11-06/known-minor-http.txt), [offline](forward-final-2026-11-06/known-minor.txt), [finding](forward-final-2026-11-06/findings.json) |
| `make down` своих project, fixture `docker compose down`, инвентаризация по labels | 0 контейнеров трёх project, 6 volumes сохранены | [main](forward-final-2026-11-06/main-down.txt), [demo](forward-final-2026-11-06/reconcile-down.txt), [итог](forward-final-2026-11-06/shutdown-state.txt) |
[Сводка чисел](forward-final-2026-11-06/measurement-summary.json),
[команда агрегации](forward-final-2026-11-06/measurement-summary.txt),
[фон до](forward-final-2026-11-06/performance-before.txt) и
[после](forward-final-2026-11-06/performance-after.txt).
Сохранены неуспешные попытки: [ty до исправления обвязки](forward-final-2026-11-06/offline-checks.txt)
и [неверный BASE_URL до hook](forward-final-2026-11-06/persistence-command.txt); они не считаются PASS.
## Исходная SQLAlchemy-серия
Runtime основы: `8e4532f6f5c05d902b6e2c310f54320d95585904`. Все результаты ниже сняты
**до F и обоих PNG-фиксов**. Обвязка менялась отдельно; точный SHA каждого захвата записан
в его первой строке/JSON. [Общий протокол](sqlalchemy-2026-11-06/README.md).
| Команда / критерий | Наблюдение | SHA обвязки и файлы |
| --- | --- | --- |
| `make test`, `make limits`, `make attachments-evidence`, LB/retry/отказы | Уровень 3 на SQLAlchemy, 404 собственных теста | `1aec062aba4560b51a6d9155571c9610bc777d7e`, `763b0255575366082c4c6731b54611af717685a5`; [grade3](sqlalchemy-2026-11-06/grade3/NOTES.md) |
| `make s3-check` | 31 PASS; private/IAM/bootstrap не менялись с этой серии | `763b0255575366082c4c6731b54611af717685a5`; [сырьё](sqlalchemy-2026-11-06/grade3/s3-security.txt) |
| `make upload-memory`, три полные матрицы | 36 точек, штатные 3 слота 840/840×201, пик 448 MiB, OOM 0; контроль 64 слота 27×503 | `6c706a727ec7b4c5f8254e19401705847e8e9c78`, `cf41f7c64dcf1dea6da0643f5793bd2e5dd1f03e`; [методика](sqlalchemy-2026-11-06/grade4/NOTES.md), [raw](sqlalchemy-2026-11-06/grade4/memory/) |
| `sh scripts/clean-clone.sh` | 76,866 с, проверки прошли, три volumes сохранены | `cf41f7c64dcf1dea6da0643f5793bd2e5dd1f03e`; [команда/вывод](sqlalchemy-2026-11-06/grade4/clean-clone-command.txt) |
| `make overload-leftovers` | Без сдвига времени убраны 30 pending после grace 900 с; 1669 ready/объектов совпали | SHA в [команде](sqlalchemy-2026-11-06/grade4/leftovers-command.txt); [вывод](sqlalchemy-2026-11-06/grade4/overload-leftovers.txt) |
| `make load-evidence` | 3 прогона, медиана 1529,186 RPS, 0 ошибок; историческая серия до F | SHA в [команде](sqlalchemy-2026-11-06/grade4/load-command.txt); [raw](sqlalchemy-2026-11-06/grade4/load/) |
| `make reconcile-demo`, отдельный отказ PG | 13 PASS, 3331 upload, lost_ready 0; обновлён demo серии F | `827b783be355be9fa60117dc3eda350af3dab454`, `3402fd69d4922e500035a204d957be2cccaeb85a`; [протокол](sqlalchemy-2026-11-06/track5/NOTES.md), [PG](sqlalchemy-2026-11-06/track5/pg-outage.txt) |
| `make reconcile-cost` | **Сохраняемые 27 замеров** до 100k; путь обхода неизменён | `3402fd69d4922e500035a204d957be2cccaeb85a`; [команда](sqlalchemy-2026-11-06/track5/cost-command.txt), [raw/план/фон](sqlalchemy-2026-11-06/track5/measurements/cost/), [расчёт](sqlalchemy-2026-11-06/track5/analysis.json) |
| Финальные проверки исходной реализации | 410 тестов, check/validate/lint/smoke/limits PASS; не тесты нового PNG | `504f77cb7cef28202e1830fc04e10e646488e778`; [вывод](sqlalchemy-2026-11-06/track5/final-checks.txt), [остановка 4 project / 12 volumes](sqlalchemy-2026-11-06/track5/shutdown-state.txt) |
[Закрытие 21 замечания исходной реализации](sqlalchemy-2026-11-06/REVIEW-CLOSURE.md)
относится к тому этапу. Оно предшествует независимым PNG-находкам и не отменяет их историю.
## Историческая реализация asyncpg
**Эти результаты не подтверждают нынешний SQLAlchemy-код или PNG-инспектор.**
Основная серия и старый clean-clone: `81dd816df21f820a7fd0fa4269cc375d8fc44155`;
reconciler: `61dcb6bf13f3d0853d36788930d79bca5f68ece6`. Дата и измеренный SHA
сохранены в raw. Старые команды удаления volumes — история, не инструкция для повторения.
| Историческая команда | Сохранённые файлы |
| --- | --- |
| `make check`, `make validate`, `make student-test`, `make test` | [контракт](contract-checks.txt), [тесты](student-tests.txt), [smoke](smoke.txt) |
| `make clean-clone-evidence`, `make stack-evidence`, `make limits`, `make attachments-evidence` | [clone](clean-clone.txt), [стенд](stack.txt), [окружение](environment.txt), [лимиты](limits.txt), [размещение](storage-layout.txt) |
| `make lb-check`, `make retry-check`, persistence и сценарии отказов | [LB](lb-check.json), [retry](retry.json), [persistence](persistence.txt), [upload failover](failover-upload.json), [S3 outage](s3-outage.json) |
| `make upload-faults`, `make faults-evidence`, `make s3-check` | [upload](upload-faults.txt), [stack](faults.txt), [S3](s3-security.txt) |
| `make upload-memory`, `make overload-leftovers`, `make load-evidence` | [память](upload-memory/), [остатки](overload-leftovers.txt), [нагрузка](load.txt), [raw](load/), [отброшенная попытка с хоста](load/host-attempt.txt) |
| `make reconcile-demo`, `make reconcile-cost` | [методика и все серии](reconcile/README.md), [raw](reconcile/), [cost](reconcile/cost/) |
Прежние cost-серии `b1916236f4391bfdf7d7718ebf741621047788cf` (лишняя SQL-страница),
`5ca2cdc9af6016df8d6f1be8bd4681f06fada334` (без фильтра фона) и прерванные наполнения
описаны в [историческом индексе reconciler](reconcile/README.md). Они не подмешиваются
к 27 принятым измерениям SQLAlchemy и не удаляются.
+132
View File
@@ -0,0 +1,132 @@
date: 2026-10-30T04:27:15Z commit: 81dd816 dir: mtusi2026lab4-clean (свой compose-проект и volumes)
# шаги — команды блока «Запуск из чистого clone» REPORT.md; строки с пометкой «наблюдение» — проверки между шагами
$ git clone <repo> mtusi2026lab4-clean && cd mtusi2026lab4-clean && git checkout solution/bpi2303-kostylev
HEAD 81dd816 Archive the storage reconciler change
$ docker volume ls -q --filter label=com.docker.compose.project=mtusi2026lab4-clean | wc -l | tr -d ' ' # наблюдение, не шаг инструкции
0
$ make secrets
sh scripts/secrets.sh
создан secrets/postgres_password
создан secrets/database_url
создан secrets/cursor_secret
создан secrets/valkey_password
создан secrets/valkey.conf
создан secrets/cache_url
создан secrets/s3_root_user
создан secrets/s3_root_password
создан secrets/s3_access_key_id
создан secrets/s3_secret_access_key
создан .env из .env.example
$ sed LB_HTTP_PORT=18084 LB_STATS_PORT=24084 .env # отступление: 8080 на этой машине занят стендами других лаб
$ git status --short --ignored secrets .env # наблюдение, не шаг инструкции
!! .env
!! secrets/
$ docker compose --env-file .env config --quiet && echo valid
valid
$ make up
Container mtusi2026lab4-clean-postgres-1 Healthy
Container mtusi2026lab4-clean-s3-1 Healthy
Container mtusi2026lab4-clean-s3-init-1 Exited
Container mtusi2026lab4-clean-migrate-1 Exited
Container mtusi2026lab4-clean-postgres-1 Healthy
Container mtusi2026lab4-clean-migrate-1 Exited
Container mtusi2026lab4-clean-valkey-1 Healthy
Container mtusi2026lab4-clean-s3-1 Healthy
Container mtusi2026lab4-clean-s3-init-1 Exited
Container mtusi2026lab4-clean-api-1 Healthy
Container mtusi2026lab4-clean-api-2 Healthy
Container mtusi2026lab4-clean-lb-1 Healthy
make up: 11 s (сборка образа из кэша слоёв)
$ docker compose ps -a --format '{{.Service}} {{.State}} {{.Status}} {{.Ports}}' # наблюдение, не шаг инструкции
api running Up 4 seconds (healthy)
api running Up 4 seconds (healthy)
lb running Up 10 seconds (healthy) 127.0.0.1:18084->8080/tcp, 127.0.0.1:24084->8404/tcp
migrate exited Exited (0) 8 seconds ago
postgres running Up 10 seconds (healthy)
s3 running Up 10 seconds (healthy)
s3-init exited Exited (0) 4 seconds ago
valkey running Up 10 seconds (healthy)
$ docker compose logs --no-log-prefix migrate s3-init | grep -v '^$' | tail -8 # наблюдение, не шаг инструкции
{"version":"0001_init","event":"migration.applied","level":"info","ts":"2026-10-30T04:27:18.183850Z"}
{"version":"0002_idempotency_keys","event":"migration.applied","level":"info","ts":"2026-10-30T04:27:18.183962Z"}
{"version":"0003_attachments","event":"migration.applied","level":"info","ts":"2026-10-30T04:27:18.184008Z"}
{"version":"0004_attachment_quarantine","event":"migration.applied","level":"info","ts":"2026-10-30T04:27:18.184039Z"}
{"reason":"applied","event":"migration.completed","level":"info","ts":"2026-10-30T04:27:18.184066Z"}
s3-init: bucket=messenger-attachments anonymous=private policy=messenger-api lifecycle=abort-incomplete-uploads
$ curl -s "http://$(docker compose port lb 8404)/stats;csv" | awk -F, '$1 == "api" && $2 != "BACKEND" {print $2, $18}' | grep -v MAINT # наблюдение, не шаг инструкции
api1 UP
api2 UP
$ make test
python3 tests/smoke.py --base-url "http://127.0.0.1:18084"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:18084"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
$ docker compose ps -a --format '{{.Service}} {{.State}} {{.RunningFor}} {{.Status}}' # наблюдение, не шаг инструкции
api running 24 seconds ago Up 3 seconds (healthy)
api running 24 seconds ago Up 3 seconds (healthy)
lb running 24 seconds ago Up 8 seconds (healthy)
migrate exited 24 seconds ago Exited (0) 7 seconds ago
postgres running 24 seconds ago Up 9 seconds (healthy)
s3 running 24 seconds ago Up 9 seconds (healthy)
s3-init exited 24 seconds ago Exited (0) 3 seconds ago
valkey running 24 seconds ago Up 9 seconds (healthy)
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:18084"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 128, "failed_attempts": 0, "first_recovery_seconds": 2.948}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
$ docker compose ps -a --format '{{.Service}} {{.Name}} {{.State}} {{.Status}}' api # наблюдение, не шаг инструкции
api mtusi2026lab4-clean-api-1 running Up 19 seconds (healthy)
api mtusi2026lab4-clean-api-2 exited Exited (0) 12 seconds ago
$ make restore
scripts/restore.sh
Container mtusi2026lab4-clean-api-1 Running
Container mtusi2026lab4-clean-api-2 Starting
Container mtusi2026lab4-clean-api-2 Started
Container mtusi2026lab4-clean-api-1 Waiting
Container mtusi2026lab4-clean-api-2 Waiting
Container mtusi2026lab4-clean-api-1 Healthy
Container mtusi2026lab4-clean-api-2 Healthy
$ make scenario SCENARIO=failover-upload
{'ok': True, 'upload_instance': 'b21945b926b7', 'download_instance': '6c9bf1e3b1a6', 'sha256_equal': True, 'hook_seconds': 2.713}
$ make scenario SCENARIO=s3-outage
{'ok': True, 'upload': 503, 'metadata': 200, 'download': 503, 'text_message': 201, 'health_ready': 200}
$ make s3-check
23
== 2026-10-30T04:28:17Z S3 privacy and bootstrap checks
== IAM/bucket snapshot (без секретов)
$ make reconcile
dry-run {'objects': 5, 'rows': 6} {'pending_fresh': 1} errors 0
$ make migrate
docker compose run --rm migrate
{"reason":"up to date","event":"migration.completed","level":"info","ts":"2026-10-30T04:28:21.735485Z"}
$ docker volume ls --format '{{.Name}}' --filter label=com.docker.compose.project=mtusi2026lab4-clean # наблюдение, не шаг инструкции
mtusi2026lab4-clean_pgdata
mtusi2026lab4-clean_s3data
mtusi2026lab4-clean_valkeydata
$ make down
1 Container mtusi2026lab4-clean-api-1 Removed
1 Container mtusi2026lab4-clean-api-2 Removed
1 Container mtusi2026lab4-clean-lb-1 Removed
1 Container mtusi2026lab4-clean-migrate-1 Removed
1 Container mtusi2026lab4-clean-postgres-1 Removed
1 Container mtusi2026lab4-clean-s3-1 Removed
1 Container mtusi2026lab4-clean-s3-init-1 Removed
1 Container mtusi2026lab4-clean-valkey-1 Removed
1 Network mtusi2026lab4-clean_backend Removed
1 Network mtusi2026lab4-clean_edge Removed
$ docker volume ls --format '{{.Name}}' --filter label=com.docker.compose.project=mtusi2026lab4-clean # наблюдение, не шаг инструкции
mtusi2026lab4-clean_pgdata
mtusi2026lab4-clean_s3data
mtusi2026lab4-clean_valkeydata
$ make reset-data
Volume mtusi2026lab4-clean_pgdata Removing
Volume mtusi2026lab4-clean_s3data Removing
Volume mtusi2026lab4-clean_valkeydata Removing
Volume mtusi2026lab4-clean_pgdata Removed
Volume mtusi2026lab4-clean_s3data Removed
Volume mtusi2026lab4-clean_valkeydata Removed
$ docker volume ls -q --filter label=com.docker.compose.project=mtusi2026lab4-clean | wc -l | tr -d ' ' # наблюдение, не шаг инструкции
0
+8 -10
View File
@@ -1,14 +1,12 @@
date: 2026-10-29T00:36:33Z commit: 0b85edf
date: 2026-10-30T04:24:13Z commit: 81dd816
$ make check
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
$ make validate PYTHON=<venv с requirements-dev.txt>
<venv>/bin/python scripts/validate_openapi.py
$ make validate # openapi-spec-validator 0.7.2 из .venv (make install)
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
$ make lint
.venv/bin/ruff check src student-tests scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/make_images.py scripts/pipeline_suite.py scripts/pipeline_evidence.py
All checks passed!
.venv/bin/ruff format --check src student-tests scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/make_images.py scripts/pipeline_suite.py scripts/pipeline_evidence.py
159 files already formatted
.venv/bin/ty check src student-tests
All checks passed!
$ git diff --stat upstream/main -- contracts tests README.md COURSE.md CONTRIBUTING.md MAINTAINERS.md lab.json compose.example.yaml Dockerfile.example # контракт, публичные тесты и задание не менялись
(пусто)
$ git diff --stat upstream/main -- .github # только свой CI job
.github/workflows/application.yml | 93 +++++++++++++++++++++++++++++++++++++++
1 file changed, 93 insertions(+)
+2 -19
View File
@@ -1,16 +1,14 @@
date: 2026-10-29T00:36:34Z commit: 0b85edf
date: 2026-10-30T04:29:05Z commit: 81dd816
host: Apple M4 Max, 16 CPU, 48 GiB RAM, macOS 15.1
docker: 28.3.2, VM: 16 CPU, 8217190400 bytes
compose: 2.38.2-desktop.1
images:
image: ${API_IMAGE:-mtusi-messenger:lab5}
image: ${API_IMAGE:-mtusi-messenger:lab5}
image: ${API_IMAGE:-mtusi-messenger:${COMPOSE_PROJECT_NAME}}
image: rustfs/rc:v0.1.36@sha256:ab024bfebee49a750ce886b4c70963ccd9ddaa03f491704a90710641d7a26699
image: haproxy:3.2.26-alpine@sha256:5893840576071e6217cd52ebdcc14f454c6f7a631056fa6f4e0f40d3cac4215b
image: postgres:17.11-alpine@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b
image: valkey/valkey:8.1.11-alpine@sha256:2602ace2be6569bc2bbb06f873776516ab9089821525be34f4305c67eb9db02a
image: rustfs/rustfs:1.0.4@sha256:ed9210d6411d77ffceb70d94b964a3cb7d225983368bc25bebe01e995293dcc2
image: rabbitmq:4.1.8-management-alpine@sha256:54ef5ff505352c1beef05a97ee9bd6ab95b3559a76629ba0119b1d63d8d6e4b2
image: grafana/k6:2.3.0@sha256:2dd4756ec6e14e62778916e1eb850108e4b499304c02df56760fa0bdb0fba0b8
FROM python:3.14-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS builder
COPY --from=ghcr.io/astral-sh/uv:0.9.7@sha256:ba4857bf2a068e9bc0e64eed8563b065908a4cd6bfb66b531a9c424c8e25e142 /uv /usr/local/bin/uv
@@ -18,7 +16,6 @@ images:
python in image: Python 3.14.7
haproxy: HAProxy version 3.2.26-3e0f11a 2026/10/14 - https://haproxy.org/
rustfs: rustfs 1.0.4
rabbitmq: 4.1.8
packages (uv.lock):
fastapi 0.141.1
uvicorn 0.54.0
@@ -35,24 +32,10 @@ packages (uv.lock):
botocore 1.43.117
aiohttp 3.14.5
pillow 13.0.0
faststream 0.7.8
aio-pika 10.2.1
aiormq 7.2.4
dishka-faststream 0.7.0
process users (service uid command):
api 10001 python
broker 100 beam.smp
broker 100 epmd
broker 100 erl_child_setup
broker 100 inet_gethost
broker 100 sh
lb 99 haproxy
postgres 70 postgres
relay 10001 docker-init
relay 10001 python
s3 10001 rustfs
valkey 999 tini
valkey 999 valkey-server
worker 10001 docker-init
worker 10001 python
worker limits: 2 CPU, memory.max 1024 MiB; render: WORKER_CONCURRENCY=2 processes, RLIMIT_AS 448 MiB, timeout 30 s, 100 tasks per process
+38
View File
@@ -0,0 +1,38 @@
date: 2026-10-30T04:29:33Z commit: 81dd816
== before: api replicas (hostname = X-Instance-Id), state, StartedAt, FinishedAt
0cc3ee358e59 running started=2026-10-30T04:28:59.851144131Z finished=0001-01-01T00:00:00Z
899a952a5a21 running started=2026-10-30T04:29:31.104320507Z finished=2026-10-30T04:29:18.153900709Z
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:18084"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 128, "failed_attempts": 0, "first_recovery_seconds": 2.883}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
== after: api replicas
0cc3ee358e59 exited started=2026-10-30T04:28:59.851144131Z finished=2026-10-30T04:29:36.57527926Z
899a952a5a21 running started=2026-10-30T04:29:31.104320507Z finished=2026-10-30T04:29:18.153900709Z
== stopped replica: 0cc3ee358e59; shutdown: signal, drain window with readiness 503, close, exit
{"event":"Handling signal: term","level":"info","ts":"2026-10-30T04:29:34.045936Z"}
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-10-30T04:29:34.072243Z"}
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-10-30T04:29:34.126665Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"6362781446fb427cbee670871ce5ef51","duration_ms":1.463,"event":"request.handled","level":"info","ts":"2026-10-30T04:29:34.446815Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"0d9cf1c47fca4ec98ed599b113cd93db","duration_ms":0.79,"event":"request.handled","level":"info","ts":"2026-10-30T04:29:34.950067Z"}
{"event":"Shutting down","level":"info","ts":"2026-10-30T04:29:36.079497Z"}
{"event":"Shutting down","level":"info","ts":"2026-10-30T04:29:36.138465Z"}
{"event":"service.stopped","level":"info","ts":"2026-10-30T04:29:36.188615Z"}
{"event":"Finished server process [20]","level":"info","ts":"2026-10-30T04:29:36.188874Z"}
{"event":"service.stopped","level":"info","ts":"2026-10-30T04:29:36.247500Z"}
{"event":"Finished server process [19]","level":"info","ts":"2026-10-30T04:29:36.247910Z"}
{"event":"Worker (pid:20) was sent SIGTERM!","level":"info","ts":"2026-10-30T04:29:36.250957Z"}
{"event":"Worker (pid:19) was sent SIGTERM!","level":"info","ts":"2026-10-30T04:29:36.357386Z"}
{"event":"Shutting down: Master","level":"info","ts":"2026-10-30T04:29:36.468491Z"}
$ scripts/restore.sh
Container mtusi2026lab4-api-2 Running
Container mtusi2026lab4-api-1 Starting
Container mtusi2026lab4-api-1 Started
Container mtusi2026lab4-api-2 Waiting
Container mtusi2026lab4-api-1 Waiting
Container mtusi2026lab4-api-2 Healthy
Container mtusi2026lab4-api-1 Healthy
== after restore
0cc3ee358e59 running started=2026-10-30T04:29:49.45750296Z finished=2026-10-30T04:29:36.57527926Z
899a952a5a21 running started=2026-10-30T04:29:31.104320507Z finished=2026-10-30T04:29:18.153900709Z
+39
View File
@@ -0,0 +1,39 @@
date: 2026-10-30T04:29:14Z commit: 81dd816
== before: api replicas (hostname = X-Instance-Id), state, StartedAt, FinishedAt
0cc3ee358e59 running started=2026-10-30T04:28:59.851144131Z finished=0001-01-01T00:00:00Z
899a952a5a21 running started=2026-10-30T04:29:11.286693179Z finished=2026-10-30T04:29:11.040183429Z
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:18084"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 129, "failed_attempts": 0, "first_recovery_seconds": 2.885}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
== after: api replicas
0cc3ee358e59 running started=2026-10-30T04:28:59.851144131Z finished=0001-01-01T00:00:00Z
899a952a5a21 exited started=2026-10-30T04:29:11.286693179Z finished=2026-10-30T04:29:18.153900709Z
== stopped replica: 899a952a5a21; shutdown: signal, drain window with readiness 503, close, exit
{"event":"Handling signal: term","level":"info","ts":"2026-10-30T04:29:15.605798Z"}
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-10-30T04:29:15.638898Z"}
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-10-30T04:29:15.701830Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"b416afb071ad426a9dde141e952d697f","duration_ms":0.823,"event":"request.handled","level":"info","ts":"2026-10-30T04:29:16.528606Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"3fe4a4c39cb24a219d3a393a1c0332f0","duration_ms":1.591,"event":"request.handled","level":"info","ts":"2026-10-30T04:29:17.038813Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"152273913ad34012bf5eaf31432490ae","duration_ms":0.263,"event":"request.handled","level":"info","ts":"2026-10-30T04:29:17.388797Z"}
{"event":"Shutting down","level":"info","ts":"2026-10-30T04:29:17.642635Z"}
{"event":"Shutting down","level":"info","ts":"2026-10-30T04:29:17.714902Z"}
{"event":"service.stopped","level":"info","ts":"2026-10-30T04:29:17.757838Z"}
{"event":"Finished server process [20]","level":"info","ts":"2026-10-30T04:29:17.758374Z"}
{"event":"Worker (pid:20) was sent SIGTERM!","level":"info","ts":"2026-10-30T04:29:17.826021Z"}
{"event":"service.stopped","level":"info","ts":"2026-10-30T04:29:17.832655Z"}
{"event":"Finished server process [13]","level":"info","ts":"2026-10-30T04:29:17.833005Z"}
{"event":"Worker (pid:13) was sent SIGTERM!","level":"info","ts":"2026-10-30T04:29:17.927620Z"}
{"event":"Shutting down: Master","level":"info","ts":"2026-10-30T04:29:18.029723Z"}
$ scripts/restore.sh
Container mtusi2026lab4-api-1 Running
Container mtusi2026lab4-api-2 Starting
Container mtusi2026lab4-api-2 Started
Container mtusi2026lab4-api-2 Waiting
Container mtusi2026lab4-api-1 Waiting
Container mtusi2026lab4-api-2 Healthy
Container mtusi2026lab4-api-1 Healthy
== after restore
0cc3ee358e59 running started=2026-10-30T04:28:59.851144131Z finished=0001-01-01T00:00:00Z
899a952a5a21 running started=2026-10-30T04:29:31.104320507Z finished=2026-10-30T04:29:18.153900709Z
+4 -4
View File
@@ -1,10 +1,10 @@
{
"ok": true,
"scenario": "failover-upload",
"upload_instance": "70cfba801128",
"download_instance": "095cb9cc85bd",
"upload_instance": "899a952a5a21",
"download_instance": "0cc3ee358e59",
"sha256_equal": true,
"hook_seconds": 2.877,
"download_ok_after_seconds": 2.886,
"hook_seconds": 2.72,
"download_ok_after_seconds": 2.73,
"restored": true
}
-39
View File
@@ -1,39 +0,0 @@
date: 2026-10-29T00:33:32Z commit: 0b85edf
== before: api replicas (hostname = X-Instance-Id), state, StartedAt, FinishedAt
095cb9cc85bd running started=2026-10-29T00:33:12.427394173Z finished=2026-10-29T00:33:03.853644169Z
70cfba801128 running started=2026-10-29T00:33:12.607365173Z finished=2026-10-29T00:33:03.666460502Z
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:18085"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 133, "failed_attempts": 0, "first_recovery_seconds": 3.005}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
== after: api replicas
095cb9cc85bd running started=2026-10-29T00:33:12.427394173Z finished=2026-10-29T00:33:03.853644169Z
70cfba801128 exited started=2026-10-29T00:33:12.607365173Z finished=2026-10-29T00:33:39.052027754Z
== stopped replica: 70cfba801128; shutdown: signal, drain window with readiness 503, close, exit
{"event":"Handling signal: term","level":"info","ts":"2026-10-29T00:33:36.479119Z"}
{"event":"Draining for 2.0 s","level":"info","ts":"2026-10-29T00:33:36.486455Z"}
{"event":"Draining for 2.0 s","level":"info","ts":"2026-10-29T00:33:36.558375Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"b3d9118f93b94471b698d536dda11072","duration_ms":0.772,"event":"request.handled","level":"info","ts":"2026-10-29T00:33:37.011026Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"3c1324def7e74f3484c4fbd242f7f70b","duration_ms":0.655,"event":"request.handled","level":"info","ts":"2026-10-29T00:33:37.515877Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"e56c9504272b45a89b7372020eb80d15","duration_ms":0.733,"event":"request.handled","level":"info","ts":"2026-10-29T00:33:37.588547Z"}
{"event":"Shutting down","level":"info","ts":"2026-10-29T00:33:38.487910Z"}
{"event":"Shutting down","level":"info","ts":"2026-10-29T00:33:38.560300Z"}
{"event":"service.stopped","level":"info","ts":"2026-10-29T00:33:38.592638Z"}
{"event":"Finished server process [13]","level":"info","ts":"2026-10-29T00:33:38.592934Z"}
{"event":"Worker (pid:13) was sent SIGTERM!","level":"info","ts":"2026-10-29T00:33:38.624866Z"}
{"event":"service.stopped","level":"info","ts":"2026-10-29T00:33:38.664775Z"}
{"event":"Finished server process [14]","level":"info","ts":"2026-10-29T00:33:38.665027Z"}
{"event":"Worker (pid:14) was sent SIGTERM!","level":"info","ts":"2026-10-29T00:33:38.725950Z"}
{"event":"Shutting down: Master","level":"info","ts":"2026-10-29T00:33:38.834487Z"}
$ scripts/restore.sh
Container mtusi2026lab5-api-1 Running
Container mtusi2026lab5-api-2 Starting
Container mtusi2026lab5-api-2 Started
Container mtusi2026lab5-api-1 Waiting
Container mtusi2026lab5-api-2 Waiting
Container mtusi2026lab5-api-1 Healthy
Container mtusi2026lab5-api-2 Healthy
== after restore
095cb9cc85bd running started=2026-10-29T00:33:12.427394173Z finished=2026-10-29T00:33:03.853644169Z
70cfba801128 running started=2026-10-29T00:33:51.687259594Z finished=2026-10-29T00:33:39.052027754Z
+106
View File
@@ -0,0 +1,106 @@
date: 2026-10-30T04:31:11Z commit: 81dd816
$ make test-faults
BASE_URL="http://127.0.0.1:18084" .venv/bin/pytest -m stack -v -s student-tests/stack
============================= test session starts ==============================
platform darwin -- Python 3.14.5, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv/bin/python
cachedir: .pytest_cache
rootdir: <repo>
configfile: pyproject.toml
plugins: asyncio-1.4.0, anyio-4.15.1
asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function
collecting ... collected 17 items
student-tests/stack/test_attachment_faults.py::test_user_errors_never_become_500 10 MiB + 1 с Content-Length, тело не отправлено: 413
10 MiB + 1 chunked: 413
PNG 100000×100000 (бомба): 413
PNG 8001×5000: 413
обрезанный PNG: 415
обрезанный JPEG: 415
JPEG как image/png: 415
GIF как image/png: 415
WebP как image/png: 415
текст как image/png: 415
PNG как image/jpeg: 415
пустое тело: 415
application/octet-stream: 415
без Content-Type: 415
filename='../a.png': 400
filename='a/b.png': 400
filename='a\\b.png': 400
filename='a\x00.png': 400
filename='a\x01.png': 400
filename='a\x7f.png': 400
filename='': 400
filename=' ': 400
filename='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: 400
filename=None: 400
посторонний: upload в чужой чат: 404
посторонний: метаданные: 404
посторонний: /content: 404
посторонний: ссылка на чужое вложение: 404
вложение другого чата: 404
неизвестное вложение: 404
11 вложений: 400
повтор вложения: 400
невалидный UUID: 400
пустой текст без вложений: 400
невалидный id вложения: 400
variant=thumbnail: 400
строк вложений в чате: 2 (= ответов 201); ответов в журнале реплик: 54, из них 5xx: 0
PASSED
student-tests/stack/test_attachment_faults.py::test_commit_failure_is_compensated_at_once отказ COMMIT после записи объекта: 503 unavailable
сразу после ответа: строка нет, объект HEAD 404
журнал: audit.attachment_discarded reason=compensation
PASSED
student-tests/stack/test_attachment_faults.py::test_crash_between_put_and_commit_is_swept_after_grace реплика 899a952a5a21 убита между PUT и COMMIT, клиент получил 502
реплика 0cc3ee358e59 убита между PUT и COMMIT, клиент получил 502
остаток после падения: строка pending, объект HEAD 200
остаток после падения: строка pending, объект HEAD 200
старше grace: строка убрана через 26.2 с, объект HEAD 404
моложе grace: строка pending, объект HEAD 200
тот же после сдвига: убран через 1.0 с, объект HEAD 404
готовое вложение в сообщении со сдвинутым created_at скачивается, SHA-256 совпадает
PASSED
student-tests/stack/test_attachment_faults.py::test_aborted_upload_leaves_nothing обрыв после 256 KiB из 5 MiB: статус в журнале реплики [400], намерение None
PASSED
student-tests/stack/test_attachment_faults.py::test_stalled_upload_is_cut_and_leaves_nothing тело зависло после 1 KiB: 503 unavailable за 8.01 с
PASSED
student-tests/stack/test_faults.py::test_registration_race_yields_exactly_one_user гонка 50 регистраций: 201×1, 409×49
PASSED
student-tests/stack/test_faults.py::test_chat_creation_rolls_back_on_unknown_member чат с несуществующим участником: 400 invalid_request
PASSED
student-tests/stack/test_faults.py::test_wrong_password_and_unknown_user_get_same_basic_challenge неверный пароль: 401 за 0.011 с
неизвестный пользователь: 401 за 0.011 с
PASSED
student-tests/stack/test_faults.py::test_logout_then_token_is_dead logout: 204, затем 401, повтор 401
PASSED
student-tests/stack/test_faults.py::test_valkey_serves_repeated_checks 5 проверок токена: keyspace_hits 119 → 124
PASSED
student-tests/stack/test_faults.py::test_valkey_stopped_is_bypassed_but_logout_waits valkey остановлен, действующий токен: 200 за 0.004 с
valkey остановлен, неизвестный токен: 401 за 0.003 с
valkey остановлен: ready 200, вход 201, выход 503
valkey снова запущен: повторный выход 204
PASSED
student-tests/stack/test_faults.py::test_valkey_restart_keeps_cache_and_revocations рестарт valkey: ключей 45 → 45
рестарт valkey: живой 200, отозванный 401
PASSED
student-tests/stack/test_faults.py::test_valkey_flushall_loses_nothing FLUSHALL: живой 200, отозванный 401
PASSED
student-tests/stack/test_faults.py::test_postgres_stopped_gives_bounded_503_and_recovers postgres остановлен, ready: 503 за 0.004 с
postgres остановлен, me: 503 за 0.003 с
postgres остановлен, stranger: 503 за 0.002 с
postgres остановлен, login: 503 за 0.002 с
postgres остановлен, register: 503 за 0.015 с
live внутри реплики 200; LB исключил все реплики ещё через 1.16 с
live через LB без реплик: 503 за 0.000 с
postgres запущен: готовность через 1.6 с, прежний токен 200
PASSED
student-tests/stack/test_faults.py::test_api_restart_keeps_session_without_extending_it рестарт api: готовность через 2.3 с, токен 200
expires_at при входе 2026-10-30T05:32:12.249834Z, в БД после рестарта 2026-10-30T05:32:12.249834Z
PASSED
student-tests/stack/test_faults.py::test_full_restart_keeps_session_until_logout restart.sh: готовность через 0.0 с, прежний токен 200, выход 204, затем 401
PASSED
student-tests/stack/test_faults.py::test_session_expires_after_restart_at_original_time срок сессии сокращён до 20 с, рестарт api: готовность через 3.1 с, до срока 200, после срока 401
PASSED
======================== 17 passed in 98.43s (0:01:38) =========================
@@ -1,57 +0,0 @@
# Повторная квалификация после позднего forward
Runtime: `0e921116610d289716af0a40ec823376eb8bbcbc`. Источник: `d7478726a85791c21e065d58f610735a9e687433..4ed889c1e4008e3f6040ae2534bef99262d3b8ce`, только immutable snapshot. Полная судьба 253 файлов — ../forward-port.md и source-inventory.json. REPORT.md не изменён: это материалы следующему агенту отчёта.
## Гипотеза и методика
Поздние исправления входной валидации, отзыва сессий и ошибок LB должны устранить конкретные регрессии, сохранив подтверждённые 202, единственность эффекта и монотонную публикацию версий pipeline. Проверяем корректность, а не прирост RPS.
На исходном f88e9ba с перенесёнными тестами получены 29 ожидаемых FAIL / 24 PASS (baseline-regressions.txt). PNG дошёл до попытки storage, вместо раннего 415; Basic/NUL не отклонялись как требуется. После переноса: 303 целевых unit PASS. `baseline.txt` — отдельная неуспешная попытка до появления файлов тестов, 0 запущенных тестов; результат не использован как проверка.
`make check validate lint`, `make student-test`: 819 PASS, 1 skip (RLIMIT_AS только Linux), 19 stack deselected. Это предкоммитные проверки рабочего diff, впоследствии зафиксированного в runtime SHA. Изменений runtime после него нет; финальные specs/evidence коммитятся отдельно. Context7 для SQLAlchemy 2.0.45 / FOR KEY SHARE использован при подготовке design.
Собственный Compose project `mtusi2026lab5`, API 127.0.0.1:18085, stats 25085, UI broker 25086; volumes сохранены между повторами. API_IMAGE=mtusi-messenger:lab5-forward. Конфигурация — compose.yaml с fault override infra/compose.faults.yaml. Параллельных нагрузок этого этапа нет; чужие контейнеры не останавливались. Host Darwin arm64 / 16 CPU; Docker 28.3.2 / 16 CPU / 8217190400 bytes RAM. NO_PROXY включает loopback. conditions-*.json содержит моментальные срезы: других проектов в них нет. Это не непрерывный мониторинг всей нагрузки хоста.
Команды, UTC, SHA, exit code и сырые результаты сохранены в одноимённых txt/json:
| Критерий | Команда | Наблюдение | Доказательство |
| --- | --- | --- | --- |
| Минимум lab1–4 / async upload | make test | PASS | smoke.txt, final-smoke.txt |
| Сохранность после рестарта | make test-persistence ACTION_SCRIPT=scripts/restart.sh | PASS; действующая сессия и исходник сохранены | persistence.txt, persistence-containers.txt |
| Отказ API | make test-failover ACTION_SCRIPT=scripts/stop-one.sh; make restore | 131 запись, 0 ошибок; api-2 Exited, затем восстановлен | failover.txt, failover-containers.txt, restore.txt |
| Basic/NUL/logout через обе реплики | python3 student-tests/tools/forward_network.py | 401/400/404 по контракту; исправленный повтор ключа без дубля; logout 204→401 | network-regressions.txt |
| Ранний отказ битого PNG и границы upload | pytest -m stack -s -q student-tests/stack/test_attachment_faults.py::test_user_errors_never_become_500 | IDAT/IHDR 415; 10 MiB принимается; строки только для 202; 123 HTTP в журнале, 0 5xx | upload-negative.txt |
| Кэш недоступен | pytest -m stack -s -q student-tests/stack/test_faults.py::test_valkey_stopped_is_bypassed_but_logout_waits | 200 через БД, неизвестный 401, logout 503; после восстановления 204 и 401 | cache-outage.txt |
| Гонки заполнения/потеря tombstone/SQL COMMIT | make student-test, api/test_cache.py + unit/test_session_cache.py | PASS, реальный одноразовый PostgreSQL/Valkey и управляемые гонки | student-test.txt, unit-regressions.txt |
| 502/503/504 с кавычкой, backslash, tab и длиной 200 | fixture hlpipe-lab5-forward-errors, 3 × probe | 12 валидных JSON; тело и header совпадают; fixture остановлен | haproxy-errors.txt |
| Уровни 3/4 | python3 scripts/pipeline_suite.py --level 4 --output evidence/forward-final-2026-11-06/level4.json | 17 сценариев, 8 инвариантов PASS; 33 IDs, 28 ready, 5 ожидаемых failed, 116 S3-объектов | level4-command.txt, level4.json |
| Лимиты Linux worker | worker_limits внутри level4 | 40 Мп, 0.5 s / 200 MiB → контролируемый failed, worker жив; штатный peak 423 MiB < 1024 MiB | level4.json |
| Трек 2 | make track2 TRACK2_OUTPUT=evidence/forward-final-2026-11-06/track-runN.json, N=1,2,3 последовательно | Все 13 сценариев и 8 инвариантов в каждом повторе PASS | track-run1/2/3.txt и .json |
## Результаты трека
В каждом повторе smoke_pipeline служит контролем без fault. Далее suite автоматически внедряет дубли, reorder attempts/versions, crash до side effect, после S3, после COMMIT до ack, разрыв outbox publish/confirm, SIGKILL worker и устаревшую job после v2. JSON содержит фактические остановленные контейнеры, принятые ID, версии, хеши и SQL/S3-инварианты.
| Повтор | Сценарии PASS | Инварианты PASS | Уникальные 202 | S3-объекты своей выборки | UTC-интервал, s | Монотонное elapsed, s |
| --- | --- | --- | --- | --- | --- | --- |
| 1 | 13 | 8 | 13 | 58 | 181.175 | 181.089 |
| 2 | 13 | 8 | 13 | 58 | 1161.195 | 186.458 |
| 3 | 13 | 8 | 13 | 58 | 571.513 | 180.259 |
Итог: 39 разных принятых вложений, 174 S3-объекта; 39 сценариев и 24 проверки инвариантов PASS. Ни потери 202, ни повторного набора вариантов, ни отката ready/published_version не обнаружено. Старый результат не перезаписывает новый.
Сравнение с сохранённой предыдущей квалификацией runtime 9ba3076fa8ba707de932e053fc22f455d83b3210: те же 3 функциональных повтора, 39 сценариев, 24 инварианта, 39 вложений и 174 объекта PASS. Сравнение показывает сохранение инвариантов после forward, а не ускорение. Старое evidence сохраняет свой SHA. Входные дефекты на f88 воспроизведены отдельно и устранены.
Доставка остаётся at-least-once: подтверждение публикации и manual ack не образуют общей транзакции с PostgreSQL. Повтор той же job нормален после окна сбоя; уникальность versioned effects, lease/fencing и монотонная SQL-публикация ограничивают побочные эффекты. Это не exactly-once доставка.
## Ограничения для итогового REPORT
- У run2/3 расходятся UTC и монотонное elapsed (clock-observation.json). Причина не установлена. Длительности сохранены как сырые наблюдения, но исключены из performance/SLO и заявлений о разбросе. Трек 2 README не требует throughput/p95; все функциональные проверки и фактические fault-injection завершились. Повторять пригодные функциональные серии оснований нет.
- Моментальные срезы Docker не доказывают отсутствие всей фоновой нагрузки хоста. Новых утверждений о RPS или сравнительной производительности нет; финальную release-нагрузку проводит назначенная фаза.
- no_orphans ограничен IDs данного прогона. Исторические failed jobs и DLQ сохранены; в конце level4 DLQ 15 сообщений, включая ожидаемый malformed message, а не глобальный ноль.
- Три прежних minor не изменились: ложный FAIL порядка secrets в scripts/limits.py; legacy scripts/reconcile_track.py для синхронной ЛР4; отсутствие отдельного retry failed upgrade v2 при ready v1. Подробности и происхождение — findings.json. Команде limits.py PASS не присвоен, она в этой фазе не запускалась.
- REPORT/AGENTS и нормативные файлы не менялись; окончательный отчёт и публикация принадлежат следующим фазам.
## Завершение стенда
Финальный smoke PASS. `make down` завершён без `-v`; основной project не содержит контейнеров, временный fixture также остановлен. Сохранены mtusi2026lab5_broker-data, mtusi2026lab5_pgdata, mtusi2026lab5_s3data, mtusi2026lab5_valkeydata (retained-volumes.txt).
@@ -1,7 +0,0 @@
date: 2026-11-06T20:15:43Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {}
$ openspec archive forward-lab4-final-review-fixes --yes --skip-specs
Task status: ✓ Complete
Skipping spec updates (--skip-specs flag provided).
Change 'forward-lab4-final-review-fixes' archived as '2026-11-06-forward-lab4-final-review-fixes'.
exit_code: 0 elapsed_seconds: 0.938
File diff suppressed because it is too large Load Diff
@@ -1,8 +0,0 @@
date: 2026-11-06T19:29:52Z commit: f88e9ba43cdfd7eb6a5a7ae5feb4247b4e820071
environment: {}
$ .venv/bin/pytest -q student-tests/unit/test_png_upload.py student-tests/unit/test_authentication.py student-tests/unit/test_nul_inputs.py
ERROR: file or directory not found: student-tests/unit/test_png_upload.py
no tests ran in 0.00s
exit_code: 4 elapsed_seconds: 1.080
@@ -1,10 +0,0 @@
date: 2026-11-06T19:41:00Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
$ .venv/bin/pytest -m stack -s -q student-tests/stack/test_faults.py::test_valkey_stopped_is_bypassed_but_logout_waits
valkey остановлен, действующий токен: 200 за 0.009 с
valkey остановлен, неизвестный токен: 401 за 0.005 с
valkey остановлен: ready 200, вход 201, выход 503
valkey снова запущен: повторный выход 204
.
1 passed in 3.99s
exit_code: 0 elapsed_seconds: 4.854
@@ -1,14 +0,0 @@
date: 2026-11-06T20:15:45Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {}
$ make check validate lint
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
.venv/bin/ruff check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py scripts/make_images.py scripts/pipeline_suite.py scripts/pipeline_evidence.py
All checks passed!
.venv/bin/ruff format --check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py scripts/make_images.py scripts/pipeline_suite.py scripts/pipeline_evidence.py
194 files already formatted
.venv/bin/ty check src student-tests alembic
All checks passed!
exit_code: 0 elapsed_seconds: 0.822
@@ -1,25 +0,0 @@
{
"observed_at": "2026-11-06T20:15:05.166068+00:00",
"runtime_sha": "0e921116610d289716af0a40ec823376eb8bbcbc",
"runs": [
{
"file": "track-run1.json",
"utc_interval_seconds": 181.175,
"capture_monotonic_seconds": 181.089,
"time_comparable": true
},
{
"file": "track-run2.json",
"utc_interval_seconds": 1161.195,
"capture_monotonic_seconds": 186.458,
"time_comparable": false
},
{
"file": "track-run3.json",
"utc_interval_seconds": 571.513,
"capture_monotonic_seconds": 180.259,
"time_comparable": false
}
],
"conclusion": "UTC and host monotonic elapsed disagree in run2/3; cause not determined. All functional assertions passed. Durations excluded from performance comparison, SLO and spread claims. README track2 has no throughput/latency target. Adjacent Docker snapshots show no other projects; no functional rerun justified."
}
@@ -1,17 +0,0 @@
{
"at": "2026-11-06T19:33:37.768460+00:00",
"runtime_sha": "0e921116610d289716af0a40ec823376eb8bbcbc",
"platform": "Darwin",
"architecture": "arm64",
"host_cpus": 16,
"host_load": [
2.90673828125,
2.244140625,
2.03662109375
],
"docker": "16 CPUs; 8217190400 bytes; 28.3.2",
"own_project": "mtusi2026lab5",
"own": [],
"other_projects": {},
"sampling": "Shared Docker snapshot; no throughput claim"
}
@@ -1,72 +0,0 @@
{
"at": "2026-11-06T19:37:39.764784+00:00",
"runtime_sha": "0e921116610d289716af0a40ec823376eb8bbcbc",
"platform": "Darwin",
"architecture": "arm64",
"host_cpus": 16,
"host_load": [
1.72900390625,
2.11865234375,
2.03466796875
],
"docker": "16 CPUs; 8217190400 bytes; 28.3.2",
"own_project": "mtusi2026lab5",
"own": [
{
"Name": "mtusi2026lab5-worker-1",
"CPUPerc": "0.15%",
"MemUsage": "123.9MiB / 1GiB",
"PIDs": "5"
},
{
"Name": "mtusi2026lab5-relay-1",
"CPUPerc": "1.23%",
"MemUsage": "107MiB / 192MiB",
"PIDs": "4"
},
{
"Name": "mtusi2026lab5-api-1",
"CPUPerc": "8.17%",
"MemUsage": "231.6MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-api-2",
"CPUPerc": "8.01%",
"MemUsage": "225MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-broker-1",
"CPUPerc": "0.19%",
"MemUsage": "95.59MiB / 512MiB",
"PIDs": "53"
},
{
"Name": "mtusi2026lab5-postgres-1",
"CPUPerc": "2.44%",
"MemUsage": "59.16MiB / 1GiB",
"PIDs": "14"
},
{
"Name": "mtusi2026lab5-lb-1",
"CPUPerc": "1.05%",
"MemUsage": "18.64MiB / 128MiB",
"PIDs": "17"
},
{
"Name": "mtusi2026lab5-s3-1",
"CPUPerc": "26.24%",
"MemUsage": "171.1MiB / 512MiB",
"PIDs": "16"
},
{
"Name": "mtusi2026lab5-valkey-1",
"CPUPerc": "1.26%",
"MemUsage": "13.09MiB / 128MiB",
"PIDs": "7"
}
],
"other_projects": {},
"sampling": "Shared Docker snapshot; no throughput claim"
}
@@ -1,72 +0,0 @@
{
"at": "2026-11-06T19:35:55.131308+00:00",
"runtime_sha": "0e921116610d289716af0a40ec823376eb8bbcbc",
"platform": "Darwin",
"architecture": "arm64",
"host_cpus": 16,
"host_load": [
2.28515625,
2.18994140625,
2.04150390625
],
"docker": "16 CPUs; 8217190400 bytes; 28.3.2",
"own_project": "mtusi2026lab5",
"own": [
{
"Name": "mtusi2026lab5-api-1",
"CPUPerc": "1.18%",
"MemUsage": "219.9MiB / 512MiB",
"PIDs": "12"
},
{
"Name": "mtusi2026lab5-worker-1",
"CPUPerc": "0.24%",
"MemUsage": "216.1MiB / 1GiB",
"PIDs": "8"
},
{
"Name": "mtusi2026lab5-api-2",
"CPUPerc": "0.37%",
"MemUsage": "200.9MiB / 512MiB",
"PIDs": "11"
},
{
"Name": "mtusi2026lab5-relay-1",
"CPUPerc": "0.91%",
"MemUsage": "106.2MiB / 192MiB",
"PIDs": "4"
},
{
"Name": "mtusi2026lab5-broker-1",
"CPUPerc": "16.07%",
"MemUsage": "154.6MiB / 512MiB",
"PIDs": "103"
},
{
"Name": "mtusi2026lab5-postgres-1",
"CPUPerc": "0.96%",
"MemUsage": "50.39MiB / 1GiB",
"PIDs": "14"
},
{
"Name": "mtusi2026lab5-lb-1",
"CPUPerc": "0.13%",
"MemUsage": "18.16MiB / 128MiB",
"PIDs": "17"
},
{
"Name": "mtusi2026lab5-s3-1",
"CPUPerc": "1.17%",
"MemUsage": "111.8MiB / 512MiB",
"PIDs": "11"
},
{
"Name": "mtusi2026lab5-valkey-1",
"CPUPerc": "0.19%",
"MemUsage": "13.07MiB / 128MiB",
"PIDs": "7"
}
],
"other_projects": {},
"sampling": "Shared Docker snapshot; no throughput claim"
}
@@ -1,17 +0,0 @@
{
"at": "2026-11-06T20:13:44.524983+00:00",
"runtime_sha": "0e921116610d289716af0a40ec823376eb8bbcbc",
"platform": "Darwin",
"architecture": "arm64",
"host_cpus": 16,
"host_load": [
3.6494140625,
3.861328125,
3.04296875
],
"docker": "16 CPUs; 8217190400 bytes; 28.3.2",
"own_project": "mtusi2026lab5",
"own": [],
"other_projects": {},
"sampling": "Shared Docker snapshot; no throughput claim"
}
@@ -1,72 +0,0 @@
{
"at": "2026-11-06T19:44:11.713768+00:00",
"runtime_sha": "0e921116610d289716af0a40ec823376eb8bbcbc",
"platform": "Darwin",
"architecture": "arm64",
"host_cpus": 16,
"host_load": [
3.2333984375,
2.62939453125,
2.30126953125
],
"docker": "16 CPUs; 8217190400 bytes; 28.3.2",
"own_project": "mtusi2026lab5",
"own": [
{
"Name": "mtusi2026lab5-relay-1",
"CPUPerc": "0.18%",
"MemUsage": "105.9MiB / 192MiB",
"PIDs": "4"
},
{
"Name": "mtusi2026lab5-worker-1",
"CPUPerc": "0.14%",
"MemUsage": "95.77MiB / 1GiB",
"PIDs": "3"
},
{
"Name": "mtusi2026lab5-api-1",
"CPUPerc": "14.11%",
"MemUsage": "246.7MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-api-2",
"CPUPerc": "14.21%",
"MemUsage": "242.7MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-broker-1",
"CPUPerc": "0.61%",
"MemUsage": "104.9MiB / 512MiB",
"PIDs": "53"
},
{
"Name": "mtusi2026lab5-postgres-1",
"CPUPerc": "1.79%",
"MemUsage": "58.75MiB / 1GiB",
"PIDs": "15"
},
{
"Name": "mtusi2026lab5-lb-1",
"CPUPerc": "1.10%",
"MemUsage": "25.59MiB / 128MiB",
"PIDs": "17"
},
{
"Name": "mtusi2026lab5-s3-1",
"CPUPerc": "0.08%",
"MemUsage": "180.5MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-valkey-1",
"CPUPerc": "0.18%",
"MemUsage": "13.31MiB / 128MiB",
"PIDs": "7"
}
],
"other_projects": {},
"sampling": "Shared Docker snapshot; no throughput claim"
}
@@ -1,72 +0,0 @@
{
"at": "2026-11-06T20:03:36.100013+00:00",
"runtime_sha": "0e921116610d289716af0a40ec823376eb8bbcbc",
"platform": "Darwin",
"architecture": "arm64",
"host_cpus": 16,
"host_load": [
3.52001953125,
2.96923828125,
2.5068359375
],
"docker": "16 CPUs; 8217190400 bytes; 28.3.2",
"own_project": "mtusi2026lab5",
"own": [
{
"Name": "mtusi2026lab5-worker-1",
"CPUPerc": "0.19%",
"MemUsage": "95.77MiB / 1GiB",
"PIDs": "3"
},
{
"Name": "mtusi2026lab5-relay-1",
"CPUPerc": "0.52%",
"MemUsage": "105.9MiB / 192MiB",
"PIDs": "4"
},
{
"Name": "mtusi2026lab5-api-1",
"CPUPerc": "1.13%",
"MemUsage": "247.5MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-api-2",
"CPUPerc": "0.74%",
"MemUsage": "243.2MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-broker-1",
"CPUPerc": "0.25%",
"MemUsage": "104.8MiB / 512MiB",
"PIDs": "53"
},
{
"Name": "mtusi2026lab5-postgres-1",
"CPUPerc": "0.99%",
"MemUsage": "55.21MiB / 1GiB",
"PIDs": "15"
},
{
"Name": "mtusi2026lab5-lb-1",
"CPUPerc": "0.97%",
"MemUsage": "25.59MiB / 128MiB",
"PIDs": "17"
},
{
"Name": "mtusi2026lab5-s3-1",
"CPUPerc": "0.03%",
"MemUsage": "175.3MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-valkey-1",
"CPUPerc": "0.20%",
"MemUsage": "13.46MiB / 128MiB",
"PIDs": "7"
}
],
"other_projects": {},
"sampling": "Shared Docker snapshot; no throughput claim"
}
@@ -1,72 +0,0 @@
{
"at": "2026-11-06T20:13:10.819292+00:00",
"runtime_sha": "0e921116610d289716af0a40ec823376eb8bbcbc",
"platform": "Darwin",
"architecture": "arm64",
"host_cpus": 16,
"host_load": [
4.41796875,
4.0205078125,
3.06396484375
],
"docker": "16 CPUs; 8217190400 bytes; 28.3.2",
"own_project": "mtusi2026lab5",
"own": [
{
"Name": "mtusi2026lab5-worker-1",
"CPUPerc": "0.27%",
"MemUsage": "95.73MiB / 1GiB",
"PIDs": "3"
},
{
"Name": "mtusi2026lab5-relay-1",
"CPUPerc": "0.53%",
"MemUsage": "106.2MiB / 192MiB",
"PIDs": "4"
},
{
"Name": "mtusi2026lab5-api-1",
"CPUPerc": "0.84%",
"MemUsage": "247.4MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-api-2",
"CPUPerc": "1.21%",
"MemUsage": "243MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-broker-1",
"CPUPerc": "0.22%",
"MemUsage": "105MiB / 512MiB",
"PIDs": "53"
},
{
"Name": "mtusi2026lab5-postgres-1",
"CPUPerc": "0.98%",
"MemUsage": "60.75MiB / 1GiB",
"PIDs": "15"
},
{
"Name": "mtusi2026lab5-lb-1",
"CPUPerc": "0.17%",
"MemUsage": "25.93MiB / 128MiB",
"PIDs": "17"
},
{
"Name": "mtusi2026lab5-s3-1",
"CPUPerc": "1.36%",
"MemUsage": "180.3MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-valkey-1",
"CPUPerc": "0.30%",
"MemUsage": "13.22MiB / 128MiB",
"PIDs": "7"
}
],
"other_projects": {},
"sampling": "Shared Docker snapshot; no throughput claim"
}
@@ -1,72 +0,0 @@
{
"at": "2026-11-06T19:41:07.614200+00:00",
"runtime_sha": "0e921116610d289716af0a40ec823376eb8bbcbc",
"platform": "Darwin",
"architecture": "arm64",
"host_cpus": 16,
"host_load": [
3.16357421875,
2.60009765625,
2.23828125
],
"docker": "16 CPUs; 8217190400 bytes; 28.3.2",
"own_project": "mtusi2026lab5",
"own": [
{
"Name": "mtusi2026lab5-worker-1",
"CPUPerc": "0.24%",
"MemUsage": "95.74MiB / 1GiB",
"PIDs": "3"
},
{
"Name": "mtusi2026lab5-relay-1",
"CPUPerc": "0.49%",
"MemUsage": "106MiB / 192MiB",
"PIDs": "4"
},
{
"Name": "mtusi2026lab5-api-1",
"CPUPerc": "0.58%",
"MemUsage": "241MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-api-2",
"CPUPerc": "0.82%",
"MemUsage": "239.4MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-broker-1",
"CPUPerc": "0.19%",
"MemUsage": "96.05MiB / 512MiB",
"PIDs": "53"
},
{
"Name": "mtusi2026lab5-postgres-1",
"CPUPerc": "0.26%",
"MemUsage": "53.82MiB / 1GiB",
"PIDs": "15"
},
{
"Name": "mtusi2026lab5-lb-1",
"CPUPerc": "0.15%",
"MemUsage": "25.61MiB / 128MiB",
"PIDs": "17"
},
{
"Name": "mtusi2026lab5-s3-1",
"CPUPerc": "0.79%",
"MemUsage": "164.7MiB / 512MiB",
"PIDs": "13"
},
{
"Name": "mtusi2026lab5-valkey-1",
"CPUPerc": "1.42%",
"MemUsage": "13.04MiB / 128MiB",
"PIDs": "7"
}
],
"other_projects": {},
"sampling": "Shared Docker snapshot; no throughput claim"
}
@@ -1,53 +0,0 @@
date: 2026-11-06T20:13:40Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
$ make down
docker compose --profile bench --profile tools --profile reconcile down
Container mtusi2026lab5-relay-1 Stopping
Container mtusi2026lab5-lb-1 Stopping
Container mtusi2026lab5-api-2 Stopping
Container mtusi2026lab5-worker-1 Stopping
Container mtusi2026lab5-api-1 Stopping
Container mtusi2026lab5-lb-1 Stopped
Container mtusi2026lab5-lb-1 Removing
Container mtusi2026lab5-worker-1 Stopped
Container mtusi2026lab5-worker-1 Removing
Container mtusi2026lab5-lb-1 Removed
Container mtusi2026lab5-relay-1 Stopped
Container mtusi2026lab5-relay-1 Removing
Container mtusi2026lab5-worker-1 Removed
Container mtusi2026lab5-relay-1 Removed
Container mtusi2026lab5-broker-1 Stopping
Container mtusi2026lab5-broker-1 Stopped
Container mtusi2026lab5-broker-1 Removing
Container mtusi2026lab5-broker-1 Removed
Container mtusi2026lab5-api-1 Stopped
Container mtusi2026lab5-api-1 Removing
Container mtusi2026lab5-api-2 Stopped
Container mtusi2026lab5-api-2 Removing
Container mtusi2026lab5-api-1 Removed
Container mtusi2026lab5-api-2 Removed
Container mtusi2026lab5-migrate-1 Stopping
Container mtusi2026lab5-s3-init-1 Stopping
Container mtusi2026lab5-valkey-1 Stopping
Container mtusi2026lab5-migrate-1 Stopped
Container mtusi2026lab5-migrate-1 Removing
Container mtusi2026lab5-s3-init-1 Stopped
Container mtusi2026lab5-s3-init-1 Removing
Container mtusi2026lab5-s3-init-1 Removed
Container mtusi2026lab5-s3-1 Stopping
Container mtusi2026lab5-migrate-1 Removed
Container mtusi2026lab5-postgres-1 Stopping
Container mtusi2026lab5-valkey-1 Stopped
Container mtusi2026lab5-valkey-1 Removing
Container mtusi2026lab5-s3-1 Stopped
Container mtusi2026lab5-s3-1 Removing
Container mtusi2026lab5-valkey-1 Removed
Container mtusi2026lab5-s3-1 Removed
Container mtusi2026lab5-postgres-1 Stopped
Container mtusi2026lab5-postgres-1 Removing
Container mtusi2026lab5-postgres-1 Removed
Network mtusi2026lab5_backend Removing
Network mtusi2026lab5_edge Removing
Network mtusi2026lab5_backend Removed
Network mtusi2026lab5_edge Removed
exit_code: 0 elapsed_seconds: 3.359
@@ -0,0 +1,43 @@
date: 2026-11-06T09:10:22Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ sh scripts/failover-evidence.sh http://127.0.0.1:18084
date: 2026-11-06T09:10:22Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
== before: api replicas (hostname = X-Instance-Id), state, StartedAt, FinishedAt
d4c8d53d7433 running started=2026-11-06T09:10:18.309662551Z finished=2026-11-06T09:10:12.020503506Z
da922ab2ea09 running started=2026-11-06T09:10:18.377623592Z finished=2026-11-06T09:10:12.004100798Z
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:18084"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 130, "failed_attempts": 0, "first_recovery_seconds": 2.883}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
== after: api replicas
d4c8d53d7433 exited started=2026-11-06T09:10:18.309662551Z finished=2026-11-06T09:10:25.313223596Z
da922ab2ea09 running started=2026-11-06T09:10:18.377623592Z finished=2026-11-06T09:10:12.004100798Z
== stopped replica: d4c8d53d7433; shutdown: signal, drain window with readiness 503, close, exit
{"event":"Handling signal: term","level":"info","ts":"2026-11-06T09:10:22.774795Z"}
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-11-06T09:10:22.776559Z"}
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-11-06T09:10:22.848442Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"c23539767f7c4ef5ba39f58a446754a2","duration_ms":1.481,"event":"request.handled","level":"info","ts":"2026-11-06T09:10:23.545632Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"60444a3eba784d839b8caccbaa24d1f2","duration_ms":0.278,"event":"request.handled","level":"info","ts":"2026-11-06T09:10:24.058530Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"5a247b2f9b304ff789354712b9c2d857","duration_ms":0.282,"event":"request.handled","level":"info","ts":"2026-11-06T09:10:24.545468Z"}
{"event":"Shutting down","level":"info","ts":"2026-11-06T09:10:24.779511Z"}
{"event":"Shutting down","level":"info","ts":"2026-11-06T09:10:24.852501Z"}
{"event":"service.stopped","level":"info","ts":"2026-11-06T09:10:24.884399Z"}
{"event":"Finished server process [19]","level":"info","ts":"2026-11-06T09:10:24.884667Z"}
{"event":"service.stopped","level":"info","ts":"2026-11-06T09:10:24.959721Z"}
{"event":"Finished server process [20]","level":"info","ts":"2026-11-06T09:10:24.959901Z"}
{"event":"Worker (pid:19) was sent SIGTERM!","level":"info","ts":"2026-11-06T09:10:24.961675Z"}
{"event":"Worker (pid:20) was sent SIGTERM!","level":"info","ts":"2026-11-06T09:10:25.072586Z"}
{"event":"Shutting down: Master","level":"info","ts":"2026-11-06T09:10:25.178811Z"}
$ scripts/restore.sh
Container hlpipe-lab4-forward-final-20261106-api-2 Running
Container hlpipe-lab4-forward-final-20261106-api-1 Starting
Container hlpipe-lab4-forward-final-20261106-api-1 Started
Container hlpipe-lab4-forward-final-20261106-api-1 Waiting
Container hlpipe-lab4-forward-final-20261106-api-2 Waiting
Container hlpipe-lab4-forward-final-20261106-api-1 Healthy
Container hlpipe-lab4-forward-final-20261106-api-2 Healthy
== after restore
d4c8d53d7433 running started=2026-11-06T09:10:38.256484379Z finished=2026-11-06T09:10:25.313223596Z
da922ab2ea09 running started=2026-11-06T09:10:18.377623592Z finished=2026-11-06T09:10:12.004100798Z
exit_code: 0 elapsed_seconds: 19.912
@@ -1,16 +0,0 @@
date: 2026-11-06T19:34:42Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
$ docker compose ps -a
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
mtusi2026lab5-api-1 mtusi-messenger:lab5-forward "python -m gunicorn …" api 54 seconds ago Up 19 seconds (healthy)
mtusi2026lab5-api-2 mtusi-messenger:lab5-forward "python -m gunicorn …" api 54 seconds ago Exited (0) 12 seconds ago
mtusi2026lab5-broker-1 rabbitmq:4.1.8-management-alpine@sha256:54ef5ff505352c1beef05a97ee9bd6ab95b3559a76629ba0119b1d63d8d6e4b2 "docker-entrypoint.s…" broker 55 seconds ago Up 24 seconds (healthy) 127.0.0.1:25086->15672/tcp
mtusi2026lab5-lb-1 haproxy:3.2.26-alpine@sha256:5893840576071e6217cd52ebdcc14f454c6f7a631056fa6f4e0f40d3cac4215b "docker-entrypoint.s…" lb 55 seconds ago Up 24 seconds (healthy) 127.0.0.1:18085->8080/tcp, 127.0.0.1:25085->8404/tcp
mtusi2026lab5-migrate-1 mtusi-messenger:lab5-forward "alembic upgrade head" migrate 54 seconds ago Exited (0) 22 seconds ago
mtusi2026lab5-postgres-1 postgres:17.11-alpine@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b "docker-entrypoint.s…" postgres 55 seconds ago Up 25 seconds (healthy)
mtusi2026lab5-relay-1 mtusi-messenger:lab5-forward "python -m messenger…" relay 54 seconds ago Up 19 seconds (healthy)
mtusi2026lab5-s3-1 rustfs/rustfs:1.0.4@sha256:ed9210d6411d77ffceb70d94b964a3cb7d225983368bc25bebe01e995293dcc2 "/entrypoint.sh rust…" s3 55 seconds ago Up 25 seconds (healthy)
mtusi2026lab5-s3-init-1 rustfs/rc:v0.1.36@sha256:ab024bfebee49a750ce886b4c70963ccd9ddaa03f491704a90710641d7a26699 "/bin/sh /s3/init.sh" s3-init 54 seconds ago Exited (0) 20 seconds ago
mtusi2026lab5-valkey-1 valkey/valkey:8.1.11-alpine@sha256:2602ace2be6569bc2bbb06f873776516ab9089821525be34f4305c67eb9db02a "tini -- docker-entr…" valkey 55 seconds ago Up 25 seconds (healthy)
mtusi2026lab5-worker-1 mtusi-messenger:lab5-forward "python -m messenger…" worker 54 seconds ago Up 19 seconds (healthy)
exit_code: 0 elapsed_seconds: 0.124
@@ -0,0 +1,39 @@
date: 2026-11-06T09:10:22Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
== before: api replicas (hostname = X-Instance-Id), state, StartedAt, FinishedAt
d4c8d53d7433 running started=2026-11-06T09:10:18.309662551Z finished=2026-11-06T09:10:12.020503506Z
da922ab2ea09 running started=2026-11-06T09:10:18.377623592Z finished=2026-11-06T09:10:12.004100798Z
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:18084"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 130, "failed_attempts": 0, "first_recovery_seconds": 2.883}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
== after: api replicas
d4c8d53d7433 exited started=2026-11-06T09:10:18.309662551Z finished=2026-11-06T09:10:25.313223596Z
da922ab2ea09 running started=2026-11-06T09:10:18.377623592Z finished=2026-11-06T09:10:12.004100798Z
== stopped replica: d4c8d53d7433; shutdown: signal, drain window with readiness 503, close, exit
{"event":"Handling signal: term","level":"info","ts":"2026-11-06T09:10:22.774795Z"}
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-11-06T09:10:22.776559Z"}
{"limit":2.0,"event":"service.draining","level":"info","ts":"2026-11-06T09:10:22.848442Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"c23539767f7c4ef5ba39f58a446754a2","duration_ms":1.481,"event":"request.handled","level":"info","ts":"2026-11-06T09:10:23.545632Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"60444a3eba784d839b8caccbaa24d1f2","duration_ms":0.278,"event":"request.handled","level":"info","ts":"2026-11-06T09:10:24.058530Z"}
{"method":"GET","route":"/health/ready","status":503,"request_id":"5a247b2f9b304ff789354712b9c2d857","duration_ms":0.282,"event":"request.handled","level":"info","ts":"2026-11-06T09:10:24.545468Z"}
{"event":"Shutting down","level":"info","ts":"2026-11-06T09:10:24.779511Z"}
{"event":"Shutting down","level":"info","ts":"2026-11-06T09:10:24.852501Z"}
{"event":"service.stopped","level":"info","ts":"2026-11-06T09:10:24.884399Z"}
{"event":"Finished server process [19]","level":"info","ts":"2026-11-06T09:10:24.884667Z"}
{"event":"service.stopped","level":"info","ts":"2026-11-06T09:10:24.959721Z"}
{"event":"Finished server process [20]","level":"info","ts":"2026-11-06T09:10:24.959901Z"}
{"event":"Worker (pid:19) was sent SIGTERM!","level":"info","ts":"2026-11-06T09:10:24.961675Z"}
{"event":"Worker (pid:20) was sent SIGTERM!","level":"info","ts":"2026-11-06T09:10:25.072586Z"}
{"event":"Shutting down: Master","level":"info","ts":"2026-11-06T09:10:25.178811Z"}
$ scripts/restore.sh
Container hlpipe-lab4-forward-final-20261106-api-2 Running
Container hlpipe-lab4-forward-final-20261106-api-1 Starting
Container hlpipe-lab4-forward-final-20261106-api-1 Started
Container hlpipe-lab4-forward-final-20261106-api-1 Waiting
Container hlpipe-lab4-forward-final-20261106-api-2 Waiting
Container hlpipe-lab4-forward-final-20261106-api-1 Healthy
Container hlpipe-lab4-forward-final-20261106-api-2 Healthy
== after restore
d4c8d53d7433 running started=2026-11-06T09:10:38.256484379Z finished=2026-11-06T09:10:25.313223596Z
da922ab2ea09 running started=2026-11-06T09:10:18.377623592Z finished=2026-11-06T09:10:12.004100798Z
@@ -0,0 +1,33 @@
date: 2026-11-06T09:13:29Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ python3 scripts/lab4_scenarios.py failover-upload --base-url http://127.0.0.1:18084 --output evidence/forward-final-2026-11-06/failover-upload.json
{
"ok": true,
"date": "2026-11-06T09:13:29Z",
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"scenario": "failover-upload",
"upload_instance": "d4c8d53d7433",
"download_instance": "da922ab2ea09",
"sha256_equal": true,
"hook_seconds": 2.734,
"download_ok_after_seconds": 2.762,
"replicas_at_download": [
{
"hostname": "d4c8d53d7433",
"status": "exited",
"exit_code": "0",
"started_at": "2026-11-06T09:12:33.47280571Z",
"finished_at": "2026-11-06T09:13:32.422358668Z"
},
{
"hostname": "da922ab2ea09",
"status": "running",
"exit_code": "0",
"started_at": "2026-11-06T09:12:33.439519377Z",
"finished_at": "2026-11-06T09:12:33.358178252Z"
}
],
"restored": false,
"replicas_after_restore": null
}
exit_code: 0 elapsed_seconds: 3.177
@@ -0,0 +1,29 @@
{
"ok": true,
"date": "2026-11-06T09:13:29Z",
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"scenario": "failover-upload",
"upload_instance": "d4c8d53d7433",
"download_instance": "da922ab2ea09",
"sha256_equal": true,
"hook_seconds": 2.734,
"download_ok_after_seconds": 2.762,
"replicas_at_download": [
{
"hostname": "d4c8d53d7433",
"status": "exited",
"exit_code": "0",
"started_at": "2026-11-06T09:12:33.47280571Z",
"finished_at": "2026-11-06T09:13:32.422358668Z"
},
{
"hostname": "da922ab2ea09",
"status": "running",
"exit_code": "0",
"started_at": "2026-11-06T09:12:33.439519377Z",
"finished_at": "2026-11-06T09:12:33.358178252Z"
}
],
"restored": false,
"replicas_after_restore": null
}
@@ -1,8 +0,0 @@
date: 2026-11-06T19:34:25Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:18085"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 131, "failed_attempts": 0, "first_recovery_seconds": 2.791}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
exit_code: 0 elapsed_seconds: 16.815
@@ -0,0 +1,35 @@
date: 2026-11-06T09:31:35Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {}
$ sh -c 'make check && make validate && make lint && openspec validate --all --strict'
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
.venv/bin/ruff check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
All checks passed!
.venv/bin/ruff format --check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
163 files already formatted
.venv/bin/ty check src student-tests alembic
All checks passed!
- Validating...
✓ change/forward-lab3-final-review-fixes
✓ spec/lab1-event-publication
✓ spec/lab1-messenger-chats
✓ spec/lab1-messenger-history
✓ spec/lab1-messenger-identity
✓ spec/lab1-service-operability
✓ spec/lab2-auth-sessions
✓ spec/lab2-dependency-failures
✓ spec/lab2-history-index
✓ spec/lab2-persistent-storage
✓ spec/lab2-session-cache
✓ spec/lab3-failover-operations
✓ spec/lab3-idempotent-messages
✓ spec/lab3-load-balancing
✓ spec/lab4-attachments
✓ spec/lab4-evidence-runs
✓ spec/lab4-object-storage
✓ spec/lab4-storage-reconciler
✓ spec/lab4-upload-resilience
Totals: 19 passed, 0 failed (19 items)
exit_code: 0 elapsed_seconds: 1.660
@@ -1,16 +0,0 @@
date: 2026-11-06T20:13:40Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
$ docker compose ps -a
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
mtusi2026lab5-api-1 mtusi-messenger:lab5-forward "python -m gunicorn …" api 39 minutes ago Up 37 minutes (healthy)
mtusi2026lab5-api-2 mtusi-messenger:lab5-forward "python -m gunicorn …" api 39 minutes ago Up 37 minutes (healthy)
mtusi2026lab5-broker-1 rabbitmq:4.1.8-management-alpine@sha256:54ef5ff505352c1beef05a97ee9bd6ab95b3559a76629ba0119b1d63d8d6e4b2 "docker-entrypoint.s…" broker 39 minutes ago Up 37 minutes (healthy) 127.0.0.1:25086->15672/tcp
mtusi2026lab5-lb-1 haproxy:3.2.26-alpine@sha256:5893840576071e6217cd52ebdcc14f454c6f7a631056fa6f4e0f40d3cac4215b "docker-entrypoint.s…" lb 39 minutes ago Up 39 minutes (healthy) 127.0.0.1:18085->8080/tcp, 127.0.0.1:25085->8404/tcp
mtusi2026lab5-migrate-1 mtusi-messenger:lab5-forward "alembic upgrade head" migrate 39 minutes ago Exited (0) 39 minutes ago
mtusi2026lab5-postgres-1 postgres:17.11-alpine@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b "docker-entrypoint.s…" postgres 39 minutes ago Up 39 minutes (healthy)
mtusi2026lab5-relay-1 mtusi-messenger:lab5-forward "python -m messenger…" relay 35 seconds ago Up 34 seconds (healthy)
mtusi2026lab5-s3-1 rustfs/rustfs:1.0.4@sha256:ed9210d6411d77ffceb70d94b964a3cb7d225983368bc25bebe01e995293dcc2 "/entrypoint.sh rust…" s3 39 minutes ago Up 37 minutes (healthy)
mtusi2026lab5-s3-init-1 rustfs/rc:v0.1.36@sha256:ab024bfebee49a750ce886b4c70963ccd9ddaa03f491704a90710641d7a26699 "/bin/sh /s3/init.sh" s3-init 39 minutes ago Exited (0) 39 minutes ago
mtusi2026lab5-valkey-1 valkey/valkey:8.1.11-alpine@sha256:2602ace2be6569bc2bbb06f873776516ab9089821525be34f4305c67eb9db02a "tini -- docker-entr…" valkey 39 minutes ago Up 32 minutes (healthy)
mtusi2026lab5-worker-1 mtusi-messenger:lab5-forward "python -m messenger…" worker 35 seconds ago Up 34 seconds (healthy)
exit_code: 0 elapsed_seconds: 0.108
@@ -1,6 +1,6 @@
date: 2026-11-06T20:13:38Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
date: 2026-11-06T09:18:22Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ make test
python3 tests/smoke.py --base-url "http://127.0.0.1:18085"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
exit_code: 0 elapsed_seconds: 1.289
python3 tests/smoke.py --base-url "http://127.0.0.1:18084"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
exit_code: 0 elapsed_seconds: 0.435
@@ -1,25 +1,7 @@
[
{
"severity": "minor",
"file": "scripts/limits.py:14",
"problem": "S3_CLIENT_SECRETS не отсортирован, declared() сравнивает с sorted(secrets). Два ложных несовпадения для s3-cli/s3-init при равных множествах имён; limits.txt exit_code=1. Реальные CPU/RAM и порты показаны в том же файле.",
"provenance": "evidence/sqlalchemy-2026-11-06/track2/findings.json; unchanged by source range"
},
{
"severity": "minor",
"file": "scripts/reconcile_track.py",
"problem": "Перенесённый демонстратор ЛР4 ожидает upload 201 и legacy prefix; не пригоден для измерений ЛР5 (унаследовано из forward-lab4-sqlalchemy-foundation/findings.json). В квалификации pipeline не используется.",
"provenance": "evidence/sqlalchemy-2026-11-06/track2/findings.json; unchanged by source range"
},
{
"severity": "minor",
"file": "src/messenger/attachments/application/pipeline.py:333",
"problem": "Если v2 завершилась failed при уже опубликованной ready v1, reprocess существующей v2 возвращает noop, а replay ориентирован на failed-вложение и для ready также noop. Старый результат доступен и не теряется; отдельное восстановление failed upgrade пока не реализовано. Основание: test_failed_new_version_keeps_ready_original и ветви ReplayAttachmentHandler/_schedule.",
"provenance": "evidence/sqlalchemy-2026-11-06/track2/findings.json; unchanged by source range"
},
{
"severity": "minor",
"file": "evidence/forward-final-2026-11-06/clock-observation.json",
"problem": "В run2/3 UTC-интервал расходится с монотонным elapsed; причина не установлена. Функциональные сценарии и инварианты PASS, времена исключены из выводов о производительности и разбросе. Трек 2 не задаёт нормативных throughput/latency метрик."
"file": "src/messenger/messaging/entrypoints/schemas.py:35",
"problem": "Непарный Unicode surrogate U+D800/U+DFFF в text принимается схемой, fingerprint вызывает PydanticSerializationError; реальный HTTP возвращает 500 internal_error. Воспроизведено на 75b93bbba5f29575d3fca1d013cc7e0770d88082: evidence/forward-final-2026-11-06/known-minor-http.txt. Сохранено без исправления по правилу minor."
}
]
@@ -1,169 +0,0 @@
{
"runtime_sha": "0e921116610d289716af0a40ec823376eb8bbcbc",
"source_final": "lab4-4ed889c1e4008e3f6040ae2534bef99262d3b8ce",
"runtime_and_test_paths": [
{
"file": "infra/haproxy/haproxy.cfg",
"source_sha256": "50a0f551f0d77462aeb25354ba72fcdc49ef2503b92054b11888f680e6245e04",
"target_sha256": "50a0f551f0d77462aeb25354ba72fcdc49ef2503b92054b11888f680e6245e04",
"equal": true
},
{
"file": "src/messenger/attachments/infrastructure/images.py",
"source_sha256": "cef5f44a9c5bea5de5fca43ee12be7e53c5137bf24646100d795cd8ef024ff6d",
"target_sha256": "4fa19abf1a98f38f6f4c3b8c390a7e62beaef9aba1a9899ee92e29e42d1e5133",
"equal": false
},
{
"file": "src/messenger/attachments/infrastructure/png.py",
"source_sha256": "50491204d8a3667371962f43830a2b53a8b478b5941238a8db211a8a77cc57ff",
"target_sha256": "50491204d8a3667371962f43830a2b53a8b478b5941238a8db211a8a77cc57ff",
"equal": true
},
{
"file": "src/messenger/identity/application/handlers.py",
"source_sha256": "7ef32d82c687045613a12ff4d3a66376bf942ac590697f9390894b01fbc3b8f2",
"target_sha256": "7ef32d82c687045613a12ff4d3a66376bf942ac590697f9390894b01fbc3b8f2",
"equal": true
},
{
"file": "src/messenger/identity/domain/values.py",
"source_sha256": "407688bf7516c617365e021ee61abffb51e462c17640062a66a636cc25c96534",
"target_sha256": "407688bf7516c617365e021ee61abffb51e462c17640062a66a636cc25c96534",
"equal": true
},
{
"file": "src/messenger/identity/entrypoints/authentication.py",
"source_sha256": "ceaf2bf6a639fd8004de101372fca37b32f13ee6cbc6e0c159e871cc54110c6a",
"target_sha256": "ceaf2bf6a639fd8004de101372fca37b32f13ee6cbc6e0c159e871cc54110c6a",
"equal": true
},
{
"file": "src/messenger/identity/infrastructure/postgres.py",
"source_sha256": "a3c4824c5eeff98e3e5d0769d5c92733ea45d1bcd5735b61cbb21b2f41975bd4",
"target_sha256": "a3c4824c5eeff98e3e5d0769d5c92733ea45d1bcd5735b61cbb21b2f41975bd4",
"equal": true
},
{
"file": "src/messenger/identity/infrastructure/valkey.py",
"source_sha256": "d7eb27d20c0b8b5c74214ea863fd9f17c64b171e1ebecf9930cd9c458a7069fa",
"target_sha256": "d7eb27d20c0b8b5c74214ea863fd9f17c64b171e1ebecf9930cd9c458a7069fa",
"equal": true
},
{
"file": "src/messenger/messaging/domain/values.py",
"source_sha256": "eebba913911ef4c533f1d9715445e1471ad538c3631548ad36c44f4c092e9e5f",
"target_sha256": "eebba913911ef4c533f1d9715445e1471ad538c3631548ad36c44f4c092e9e5f",
"equal": true
},
{
"file": "student-tests/api/test_attachments.py",
"source_sha256": "aa85859184f532c4112aaf39c21d4e2c8f2ca60e3dee701fb37a24aa4296c60b",
"target_sha256": "e3eacfad65d93951d40fbb1b2dbe4ddccbde98d9f00c92f82ce72d2fbbc8f88b",
"equal": false
},
{
"file": "student-tests/api/test_cache.py",
"source_sha256": "ed62c0084dab3087a9d221fb52e2d67f3bc2c9d12c1bb0417627e6bca105a299",
"target_sha256": "ed62c0084dab3087a9d221fb52e2d67f3bc2c9d12c1bb0417627e6bca105a299",
"equal": true
},
{
"file": "student-tests/api/test_nul_validation.py",
"source_sha256": "f6dbd33aad5463f183ccfb295caa7d5aabd4ced0fbdf65202ef22ed540cadec0",
"target_sha256": "f6dbd33aad5463f183ccfb295caa7d5aabd4ced0fbdf65202ef22ed540cadec0",
"equal": true
},
{
"file": "student-tests/api/test_sessions.py",
"source_sha256": "bf63df875358990a8c6437797f0c56212cd608bddebb0c8fa5454f694118b059",
"target_sha256": "bf63df875358990a8c6437797f0c56212cd608bddebb0c8fa5454f694118b059",
"equal": true
},
{
"file": "student-tests/pictures.py",
"source_sha256": "fd2fe8997eaaad05082c7617aa8ece7fca0712117484f3fa3e875f701e5736b9",
"target_sha256": "fd2fe8997eaaad05082c7617aa8ece7fca0712117484f3fa3e875f701e5736b9",
"equal": true
},
{
"file": "student-tests/stack/test_attachment_faults.py",
"source_sha256": "3b56532453e92a6c66b3946570d529fe712d106543d0882335b9d423c1bfdd14",
"target_sha256": "3255caebb58c14bed5638f111eef3c55f35b3f34f9ea453f21f66d4c531d63cd",
"equal": false
},
{
"file": "student-tests/tools/forward_network.py",
"source_sha256": "2af7c53bcf74100685d3f89fbcbfa5d28ee2e10b4dd144c763e67fc2350ddc21",
"target_sha256": "19a80def7e5a1e79eca871ea264094f0c643e61d0cb1cfbfad67ab4196c516dd",
"equal": false
},
{
"file": "student-tests/tools/lb_errors/client.py",
"source_sha256": "7759bf22bbf122b4e1f54548a0e8a55f2ac42e42d8f482c95db2dc107aca6379",
"target_sha256": "7759bf22bbf122b4e1f54548a0e8a55f2ac42e42d8f482c95db2dc107aca6379",
"equal": true
},
{
"file": "student-tests/tools/lb_errors/compose.yaml",
"source_sha256": "169c98e8a22cb37426824f6aee7b76a08e40b34cf9822caa7f1ecefe25e4f6b2",
"target_sha256": "b3ba612546cf23bb202456b2935f621d8a9cad43a556f27cfd93807273c3a7e3",
"equal": false
},
{
"file": "student-tests/tools/lb_errors/server.py",
"source_sha256": "ce779c03f48f1ce671e8c65cc7b8a81d8e765d687de78433e114e5e792dbeced",
"target_sha256": "ce779c03f48f1ce671e8c65cc7b8a81d8e765d687de78433e114e5e792dbeced",
"equal": true
},
{
"file": "student-tests/unit/test_authentication.py",
"source_sha256": "c03b4860cc3ad9cebf1589d0ac1adcde190f6a30f011357bdad219b1ca7cc1f0",
"target_sha256": "c03b4860cc3ad9cebf1589d0ac1adcde190f6a30f011357bdad219b1ca7cc1f0",
"equal": true
},
{
"file": "student-tests/unit/test_haproxy_errors.py",
"source_sha256": "d1b76a39608ddf9134b9f48a467c95983e4adf6556a52115c8299bdf3489dfcb",
"target_sha256": "d1b76a39608ddf9134b9f48a467c95983e4adf6556a52115c8299bdf3489dfcb",
"equal": true
},
{
"file": "student-tests/unit/test_image_inspection.py",
"source_sha256": "05e408957a46f4fbdd77b6d5401f0374f758cc8826d7b717f600c91582d40480",
"target_sha256": "05e408957a46f4fbdd77b6d5401f0374f758cc8826d7b717f600c91582d40480",
"equal": true
},
{
"file": "student-tests/unit/test_nul_inputs.py",
"source_sha256": "43f0088c95440fa90c43b40b5ad19db4ffa28bf1a198b385b104495d259bcb93",
"target_sha256": "43f0088c95440fa90c43b40b5ad19db4ffa28bf1a198b385b104495d259bcb93",
"equal": true
},
{
"file": "student-tests/unit/test_png_upload.py",
"source_sha256": "a185767a118d3a50358de0e27d125efd4a413c518bb25f4e029fbf45fb5b0aea",
"target_sha256": "a185767a118d3a50358de0e27d125efd4a413c518bb25f4e029fbf45fb5b0aea",
"equal": true
},
{
"file": "student-tests/unit/test_session_cache.py",
"source_sha256": "64be3f10ef6dba6c0258eef1a5cb8b73450da7eca95bdc4d28484e96db160ef0",
"target_sha256": "64be3f10ef6dba6c0258eef1a5cb8b73450da7eca95bdc4d28484e96db160ef0",
"equal": true
}
],
"protected_unchanged": [
"contracts",
"tests",
"README.md",
"COURSE.md",
"REPORT.md",
"AGENTS.md",
"src/messenger/attachments/application/pipeline.py",
"src/messenger/attachments/infrastructure/postgres.py",
"src/messenger/worker.py",
"src/messenger/relay.py"
],
"source_snapshot_head": "4ed889c1e4008e3f6040ae2534bef99262d3b8ce"
}
@@ -0,0 +1,49 @@
date: 2026-11-06T09:30:40Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {}
$ python3 -c 'import collections
import json
import subprocess
from pathlib import Path
source = Path("/Users/artemkostylev/projects/learning/HL/labs/.pipeline/.runs/labs/snapshots/lab3-ba78cf6da439a4ec60fd59389583b38285b0b2b1")
manifest = json.loads(Path("evidence/forward-final-2026-11-06/source-manifest.json").read_text())
def source_git(*args):
return subprocess.check_output(["git", "-C", str(source), *args], text=True)
assert source_git("rev-parse", "HEAD").strip() == manifest["source_to"]
changed = dict(line.split("\t", 1)[::-1] for line in source_git("diff", "--name-status", manifest["source_from"], manifest["source_to"]).splitlines())
assert changed == {row["file"]: row["status"] for row in manifest["files"]}
blobs = {}
for line in source_git("ls-tree", "-r", manifest["source_to"]).splitlines():
meta, path = line.split("\t", 1)
blobs[path] = meta.split()[2]
merged = {"infra/haproxy/haproxy.cfg", "src/messenger/messaging/domain/values.py"}
exact = 0
for row in manifest["files"]:
assert blobs[row["file"]] == row["source_blob"], row["file"]
if row["action"] == "copied-source-archive" or (row["action"] == "ported" and row["file"] not in merged):
assert Path(row["file"]).read_bytes() == (source / row["file"]).read_bytes(), row["file"]
exact += 1
print(json.dumps({"source_from":manifest["source_from"], "source_to":manifest["source_to"], "manifest_paths":len(changed), "decisions":dict(collections.Counter(row["action"] for row in manifest["files"])), "byte_exact_paths":exact, "manual_lab4_merges":sorted(merged)}, indent=2))
subprocess.run(["git", "diff", "--exit-code", manifest["target_base"], "--", "contracts", "tests", "README.md", "COURSE.md"], check=True)
subprocess.run(["git", "diff", "--exit-code", "75b93bbba5f29575d3fca1d013cc7e0770d88082", "--", "src", "student-tests", "infra", "scripts", "compose.yaml", "Dockerfile", "pyproject.toml", "uv.lock", "alembic"], check=True)
print("PASS: complete immutable-source manifest, preserved normative files, runtime unchanged since measurements")
'
{
"source_from": "f591fa64e525679a31c9db7f942d36c789e1a12f",
"source_to": "ba78cf6da439a4ec60fd59389583b38285b0b2b1",
"manifest_paths": 214,
"decisions": {
"adapted-context": 2,
"not-copied": 169,
"adapted-test-tool": 4,
"ported": 14,
"copied-source-archive": 19,
"merged-via-local-change": 6
},
"byte_exact_paths": 31,
"manual_lab4_merges": [
"infra/haproxy/haproxy.cfg",
"src/messenger/messaging/domain/values.py"
]
}
PASS: complete immutable-source manifest, preserved normative files, runtime unchanged since measurements
exit_code: 0 elapsed_seconds: 0.195
@@ -1,49 +1,48 @@
date: 2026-11-06T19:34:55Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
$ sh -c 'set -e
fixture() { docker compose -p hlpipe-lab5-forward-errors -f student-tests/tools/lb_errors/compose.yaml "$@"; }
trap "fixture down" EXIT
fixture up -d lb api
fixture run --rm --no-deps probe 502
fixture run --rm --no-deps probe 504
fixture stop api
fixture run --rm --no-deps probe 503
fixture ps -a'
Network hlpipe-lab5-forward-errors_default Creating
Network hlpipe-lab5-forward-errors_default Created
Container hlpipe-lab5-forward-errors-lb-1 Creating
Container hlpipe-lab5-forward-errors-api-1 Creating
Container hlpipe-lab5-forward-errors-api-1 Created
Container hlpipe-lab5-forward-errors-lb-1 Created
Container hlpipe-lab5-forward-errors-lb-1 Starting
Container hlpipe-lab5-forward-errors-api-1 Starting
Container hlpipe-lab5-forward-errors-api-1 Started
Container hlpipe-lab5-forward-errors-lb-1 Started
{"status": 502, "request_id": "a\"b", "json_valid": true, "echo_matches": true, "seconds": 0.002}
{"status": 502, "request_id": "a\\b", "json_valid": true, "echo_matches": true, "seconds": 0.002}
{"status": 502, "request_id": "a\tb", "json_valid": true, "echo_matches": true, "seconds": 0.002}
date: 2026-11-06T09:14:49Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:hlpipe-lab4-forward-final-20261106"}
$ sh -c '
set -e
fixture_project=hlpipe-lab4-forward-lb-20261106
fixture_file=student-tests/tools/lb_errors/compose.yaml
trap '"'"'docker compose -p "$fixture_project" -f "$fixture_file" --profile probe down'"'"' EXIT
docker compose -p "$fixture_project" -f "$fixture_file" up -d lb api
docker compose -p "$fixture_project" -f "$fixture_file" run --rm --no-deps probe 502
docker compose -p "$fixture_project" -f "$fixture_file" run --rm --no-deps probe 504
docker compose -p "$fixture_project" -f "$fixture_file" stop api
docker compose -p "$fixture_project" -f "$fixture_file" run --rm --no-deps probe 503
'
Network hlpipe-lab4-forward-lb-20261106_default Creating
Network hlpipe-lab4-forward-lb-20261106_default Created
Container hlpipe-lab4-forward-lb-20261106-lb-1 Creating
Container hlpipe-lab4-forward-lb-20261106-api-1 Creating
Container hlpipe-lab4-forward-lb-20261106-api-1 Created
Container hlpipe-lab4-forward-lb-20261106-lb-1 Created
Container hlpipe-lab4-forward-lb-20261106-api-1 Starting
Container hlpipe-lab4-forward-lb-20261106-lb-1 Starting
Container hlpipe-lab4-forward-lb-20261106-lb-1 Started
Container hlpipe-lab4-forward-lb-20261106-api-1 Started
{"status": 502, "request_id": "a\"b", "json_valid": true, "echo_matches": true, "seconds": 0.001}
{"status": 502, "request_id": "a\\b", "json_valid": true, "echo_matches": true, "seconds": 0.001}
{"status": 502, "request_id": "a\tb", "json_valid": true, "echo_matches": true, "seconds": 0.001}
{"status": 502, "request_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "json_valid": true, "echo_matches": true, "seconds": 0.001}
{"status": 504, "request_id": "a\"b", "json_valid": true, "echo_matches": true, "seconds": 10.005}
{"status": 504, "request_id": "a\\b", "json_valid": true, "echo_matches": true, "seconds": 10.009}
{"status": 504, "request_id": "a\tb", "json_valid": true, "echo_matches": true, "seconds": 10.015}
{"status": 504, "request_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "json_valid": true, "echo_matches": true, "seconds": 10.009}
Container hlpipe-lab5-forward-errors-api-1 Stopping
Container hlpipe-lab5-forward-errors-api-1 Stopped
{"status": 504, "request_id": "a\"b", "json_valid": true, "echo_matches": true, "seconds": 10.024}
{"status": 504, "request_id": "a\\b", "json_valid": true, "echo_matches": true, "seconds": 10.005}
{"status": 504, "request_id": "a\tb", "json_valid": true, "echo_matches": true, "seconds": 10.022}
{"status": 504, "request_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "json_valid": true, "echo_matches": true, "seconds": 10.007}
Container hlpipe-lab4-forward-lb-20261106-api-1 Stopping
Container hlpipe-lab4-forward-lb-20261106-api-1 Stopped
{"status": 503, "request_id": "a\"b", "json_valid": true, "echo_matches": true, "seconds": 0.004}
{"status": 503, "request_id": "a\\b", "json_valid": true, "echo_matches": true, "seconds": 0.0}
{"status": 503, "request_id": "a\tb", "json_valid": true, "echo_matches": true, "seconds": 0.0}
{"status": 503, "request_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "json_valid": true, "echo_matches": true, "seconds": 0.0}
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
hlpipe-lab5-forward-errors-api-1 mtusi-messenger:lab5-forward "python /fixture/ser…" api 49 seconds ago Exited (143) 5 seconds ago
hlpipe-lab5-forward-errors-lb-1 haproxy:3.2.26-alpine@sha256:5893840576071e6217cd52ebdcc14f454c6f7a631056fa6f4e0f40d3cac4215b "docker-entrypoint.s…" lb 49 seconds ago Up 48 seconds
Container hlpipe-lab5-forward-errors-lb-1 Stopping
Container hlpipe-lab5-forward-errors-api-1 Stopping
Container hlpipe-lab5-forward-errors-api-1 Stopped
Container hlpipe-lab5-forward-errors-api-1 Removing
Container hlpipe-lab5-forward-errors-api-1 Removed
Container hlpipe-lab5-forward-errors-lb-1 Stopped
Container hlpipe-lab5-forward-errors-lb-1 Removing
Container hlpipe-lab5-forward-errors-lb-1 Removed
Network hlpipe-lab5-forward-errors_default Removing
Network hlpipe-lab5-forward-errors_default Removed
exit_code: 0 elapsed_seconds: 52.862
Container hlpipe-lab4-forward-lb-20261106-api-1 Stopping
Container hlpipe-lab4-forward-lb-20261106-lb-1 Stopping
Container hlpipe-lab4-forward-lb-20261106-api-1 Stopped
Container hlpipe-lab4-forward-lb-20261106-api-1 Removing
Container hlpipe-lab4-forward-lb-20261106-api-1 Removed
Container hlpipe-lab4-forward-lb-20261106-lb-1 Stopped
Container hlpipe-lab4-forward-lb-20261106-lb-1 Removing
Container hlpipe-lab4-forward-lb-20261106-lb-1 Removed
Network hlpipe-lab4-forward-lb-20261106_default Removing
Network hlpipe-lab4-forward-lb-20261106_default Removed
exit_code: 0 elapsed_seconds: 52.831
@@ -1,16 +0,0 @@
date: 2026-11-06T20:13:40Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
$ docker compose images
CONTAINER REPOSITORY TAG PLATFORM IMAGE ID SIZE CREATED
mtusi2026lab5-api-1 mtusi-messenger lab5-forward linux/arm64 44b21448c1e7 103MB 39 minutes ago
mtusi2026lab5-api-2 mtusi-messenger lab5-forward linux/arm64 44b21448c1e7 103MB 39 minutes ago
mtusi2026lab5-broker-1 rabbitmq <none> linux/arm64/v8 54ef5ff50535 86.3MB 9 days ago
mtusi2026lab5-lb-1 haproxy <none> linux/arm64/v8 589384057607 18.2MB 9 days ago
mtusi2026lab5-migrate-1 mtusi-messenger lab5-forward linux/arm64 44b21448c1e7 103MB 39 minutes ago
mtusi2026lab5-postgres-1 postgres <none> linux/arm64/v8 266d3c257594 115MB 9 days ago
mtusi2026lab5-relay-1 mtusi-messenger lab5-forward linux/arm64 44b21448c1e7 103MB 39 minutes ago
mtusi2026lab5-s3-1 rustfs/rustfs <none> linux/arm64 ed9210d6411d 110MB 9 days ago
mtusi2026lab5-s3-init-1 rustfs/rc <none> linux/arm64 ab024bfebee4 21.3MB 9 days ago
mtusi2026lab5-valkey-1 valkey/valkey <none> linux/arm64 2602ace2be65 17.9MB 9 days ago
mtusi2026lab5-worker-1 mtusi-messenger lab5-forward linux/arm64 44b21448c1e7 103MB 39 minutes ago
exit_code: 0 elapsed_seconds: 0.177
@@ -0,0 +1,24 @@
date: 2026-11-06T09:15:37Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {}
$ python3 -c 'import base64,http.client,json,uuid
conn=http.client.HTTPConnection("127.0.0.1",18084,timeout=10)
name="surrogate_"+uuid.uuid4().hex[:12]
password=uuid.uuid4().hex
def request(method,path,body=None,headers=None):
conn.request(method,path,None if body is None else json.dumps(body).encode(),{"Content-Type":"application/json",**(headers or {})})
response=conn.getresponse()
return response.status,json.loads(response.read() or "null")
status,user=request("POST","/api/v1/users",{"username":name,"password":password,"display_name":"Synthetic"})
assert status==201
status,session=request("POST","/api/v1/auth/sessions",headers={"Authorization":"Basic "+base64.b64encode((name+":"+password).encode()).decode()})
assert status==201
headers={"Authorization":"Bearer "+session["token"]}
status,chat=request("POST","/api/v1/chats",{"title":"Synthetic","member_ids":[user["id"]]},headers)
assert status==201
for value in [chr(0xd800),chr(0xdfff)]:
status,data=request("POST","/api/v1/chats/"+chat["id"]+"/messages",{"text":value},{**headers,"Idempotency-Key":uuid.uuid4().hex})
print(json.dumps({"codepoint":hex(ord(value)),"status":status,"error_code":data.get("error",{}).get("code")}))
conn.close()'
{"codepoint": "0xd800", "status": 500, "error_code": "internal_error"}
{"codepoint": "0xdfff", "status": 500, "error_code": "internal_error"}
exit_code: 0 elapsed_seconds: 0.114
@@ -0,0 +1,15 @@
date: 2026-11-06T09:09:38Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {}
$ .venv/bin/python -c 'import json
from messenger.messaging.entrypoints.schemas import CreateMessageRequest
for value in [chr(0xd800), chr(0xdfff)]:
body = CreateMessageRequest(text=value)
try:
body.fingerprint()
result = "accepted"
except Exception as error:
result = type(error).__name__
print(json.dumps({"codepoint": hex(ord(value)), "schema_accepted": True, "fingerprint_result": result}))'
{"codepoint": "0xd800", "schema_accepted": true, "fingerprint_result": "PydanticSerializationError"}
{"codepoint": "0xdfff", "schema_accepted": true, "fingerprint_result": "PydanticSerializationError"}
exit_code: 0 elapsed_seconds: 0.124
@@ -1,39 +0,0 @@
date: 2026-11-06T19:35:55Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
$ python3 scripts/pipeline_suite.py --level 4 --output evidence/forward-final-2026-11-06/level4.json
RUN smoke_pipeline
PASS smoke_pipeline
RUN worker_down_broker_restart
PASS worker_down_broker_restart
RUN duplicate_after_ready
PASS duplicate_after_ready
RUN poison_image
PASS poison_image
RUN s3_outage_recovers
PASS s3_outage_recovers
RUN retry_exhausted
PASS retry_exhausted
RUN image_matrix
PASS image_matrix
RUN crash_commit_publish
PASS crash_commit_publish
RUN crash_publish_confirm
PASS crash_publish_confirm
RUN crash_after_s3_before_commit
PASS crash_after_s3_before_commit
RUN crash_after_commit_before_ack
PASS crash_after_commit_before_ack
RUN lease_expiry_fencing
PASS lease_expiry_fencing
RUN replay_failed
PASS replay_failed
RUN malformed_message_dead_lettered
PASS malformed_message_dead_lettered
RUN worker_limits
PASS worker_limits
RUN retry_backoff_jitter
PASS retry_backoff_jitter
RUN failed_retention
PASS failed_retention
PASS: lab5 pipeline suite, report evidence/forward-final-2026-11-06/level4.json
exit_code: 0 elapsed_seconds: 278.951
@@ -1,977 +0,0 @@
{
"suite": "lab5-pipeline-idempotency",
"started_at": "2026-11-06T19:35:55.519173Z",
"source_sha": "0e921116610d289716af0a40ec823376eb8bbcbc",
"config": {
"base_url": "http://127.0.0.1:18085",
"level": 4,
"only": "",
"expect_variants": "thumbnail,crop,optimized",
"max_attempts": 5,
"stall_seconds": 15.0,
"compose": "docker compose",
"compose_faults": "docker compose -f compose.yaml -f infra/compose.faults.yaml"
},
"invariants": [
{
"id": "terminal",
"statement": "every 202 reaches its expected terminal state",
"result": "PASS",
"details": {
"accepted": 33
}
},
{
"id": "single_effect",
"statement": "one variant set per (attachment_id, pipeline_version, variant)",
"result": "PASS",
"details": {
"rows": 0
}
},
{
"id": "no_ready_rollback",
"statement": "ready never returns to queued or processing",
"result": "PASS",
"details": {
"traced": 33
}
},
{
"id": "monotonic_publication",
"statement": "published_version only moves forward",
"result": "PASS",
"details": {
"sampled": 8
}
},
{
"id": "bytes_match_metadata",
"statement": "sha256, size and real dimensions match served bytes",
"result": "PASS",
"details": {
"verified": 28
}
},
{
"id": "bounded_attempts",
"statement": "attempt <= JOB_MAX_ATTEMPTS",
"result": "PASS",
"details": {
"rows": 0
}
},
{
"id": "no_orphans",
"statement": "no pending outbox, messages, dead letters, staging, objects",
"result": "PASS",
"details": {
"queues": {
"attachments.process": [
0,
0
],
"attachments.process.dlq": [
15,
0
]
},
"s3_objects": 116,
"scoped_attachments": 33
}
},
{
"id": "no_lost_202",
"statement": "every 202 is present in PostgreSQL and the API",
"result": "PASS",
"details": {
"accepted": 33
}
}
],
"accepted_ids": [
"01a1b25c-6798-701c-9cd8-75aafd903a0b",
"01a1b25c-6d79-72a3-8572-6e1ce6d2fa72",
"01a1b25c-ac61-757a-8b1c-959fc5c8da61",
"01a1b25c-d0e5-7072-9e24-986d0eacf1e5",
"01a1b25d-0cd9-70fb-b193-7e4ea731dd2e",
"01a1b25d-45d0-7777-b11c-df61772945cf",
"01a1b25d-4af2-76e5-9f8d-6ebe867595c3",
"01a1b25d-5004-7706-a258-f9ccb0799e51",
"01a1b25d-5165-702a-b711-f49224657d64",
"01a1b25d-5414-742d-94e5-4cfabc6d8db2",
"01a1b25d-557a-7727-a742-a1bf9e6dbcef",
"01a1b25d-582b-779a-92fa-76c631891b36",
"01a1b25d-5992-7160-b247-ba1e57c9f68b",
"01a1b25d-5c32-70df-83ba-c52bfcd6db76",
"01a1b25d-5d9f-701a-a08a-fa64fc29fdee",
"01a1b25d-603d-76f3-896b-c0ab9922cf83",
"01a1b25d-619a-7536-b909-72ff0ebf6d5a",
"01a1b25d-642e-77e4-a17b-887d1f55d538",
"01a1b25d-6595-75ea-a2b6-bb8ff5cbca60",
"01a1b25d-682a-7350-8e9b-9fa1179383d9",
"01a1b25d-6992-70e5-972e-f93c23b8dbf6",
"01a1b25d-6c92-7370-ac06-b7d943345d62",
"01a1b25d-7d90-757d-a6cf-f374e63cf7cb",
"01a1b25d-a31a-7261-975c-7bde40c0e108",
"01a1b25d-c77d-705e-b838-9d9ba15fbadf",
"01a1b25d-f8da-76d9-b714-f7b55947a801",
"01a1b25e-2176-73e5-8d6d-34386191c57a",
"01a1b25e-a2f3-754b-982c-49da221caf59",
"01a1b25f-1ffa-72fb-8c1c-fca83d40d0fb",
"01a1b25f-31a6-7720-bd4f-60787194d5e5",
"01a1b25f-44b2-755b-a71e-634205be8c09",
"01a1b25f-5abe-7238-b0b2-db991857b384",
"01a1b25f-a149-70cd-8c7f-dfd4ec7c8883"
],
"scenarios": [
{
"name": "smoke_pipeline",
"level": 3,
"window": "upload, ready, variants match metadata",
"seconds": 1.1,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25c-6798-701c-9cd8-75aafd903a0b",
"variants": [
"crop",
"optimized",
"thumbnail"
]
}
},
{
"name": "worker_down_broker_restart",
"level": 3,
"window": "worker down, API and broker restart",
"seconds": 16.6,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25c-6d79-72a3-8572-6e1ce6d2fa72",
"timeline": [
{
"at": "2026-11-06T19:36:04.210289Z",
"step": "worker stopped",
"containers": [
"mtusi2026lab5-worker-1 3924574b030d exited Exited (0) Less than a second ago"
]
},
{
"at": "2026-11-06T19:36:04.231533Z",
"step": "upload 202 queued",
"attachment_id": "01a1b25c-6d79-72a3-8572-6e1ce6d2fa72"
},
{
"at": "2026-11-06T19:36:04.235473Z",
"step": "content 409 while queued"
},
{
"at": "2026-11-06T19:36:04.257866Z",
"step": "message with attachment 201, other messages work",
"message_id": "01a1b25c-6d8b-723f-9bef-f42c91f1c442"
},
{
"at": "2026-11-06T19:36:06.523597Z",
"step": "job is in the broker queue",
"queues": {
"attachments.process": [
1,
0
],
"attachments.process.dlq": [
14,
0
]
}
},
{
"at": "2026-11-06T19:36:12.043233Z",
"step": "API replicas and relay restarted"
},
{
"at": "2026-11-06T19:36:17.374725Z",
"step": "broker restarted with its volume, job survived",
"queues": {
"attachments.process": [
1,
0
],
"attachments.process.dlq": [
14,
0
]
}
},
{
"at": "2026-11-06T19:36:20.143149Z",
"step": "worker started"
},
{
"at": "2026-11-06T19:36:20.313903Z",
"step": "ready",
"variants": [
"crop",
"optimized",
"thumbnail"
]
}
]
}
},
{
"name": "duplicate_after_ready",
"level": 3,
"window": "redelivery of a finished job",
"seconds": 9.0,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25c-ac61-757a-8b1c-959fc5c8da61",
"events": [
{
"kind": "enqueued",
"attempt": 1
},
{
"kind": "claimed",
"attempt": 1
},
{
"kind": "done",
"attempt": 1
},
{
"kind": "duplicate_noop",
"attempt": 1
}
]
}
},
{
"name": "poison_image",
"level": 3,
"window": "permanent error without retries",
"seconds": 0.0,
"result": "PASS",
"observed": {
"rejected_by_api": 415
}
},
{
"name": "s3_outage_recovers",
"level": 3,
"window": "transient error with retry",
"seconds": 12.0,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25c-d0e5-7072-9e24-986d0eacf1e5",
"jobs": [
{
"job_id": "01a1b25c-d0ec-7129-babc-51241a730c94",
"pipeline_version": 1,
"status": "done",
"attempt": 2
}
]
}
},
{
"name": "retry_exhausted",
"level": 3,
"window": "transient error until JOB_MAX_ATTEMPTS",
"seconds": 17.6,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25d-0cd9-70fb-b193-7e4ea731dd2e",
"jobs": [
{
"job_id": "01a1b25d-0ce5-71be-bcde-4db51cbd6a9f",
"pipeline_version": 1,
"status": "failed",
"attempt": 5
}
]
}
},
{
"name": "image_matrix",
"level": 4,
"window": "limits and variants",
"seconds": 11.2,
"result": "PASS",
"observed": {
"images": [
{
"file": "png-rgb-320x200.png",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "png-rgba-300x300.png",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "png-palette-trns-200x100.png",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "png-gray-17x1000.png",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "png-gray-alpha-640x480.png",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "png-gray16-300x200.png",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "png-rgba16-64x64.png",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "png-1x1.png",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "png-wide-3000x2.png",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "png-small-50x30.png",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "jpeg-rgb-1000x750.jpg",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "jpeg-gray-801x601.jpg",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "jpeg-cmyk-400x300.jpg",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "jpeg-exif6-400x200.jpg",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "jpeg-exif3-300x200.jpg",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "jpeg-rgb-4000x3000.jpg",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "png-exactly-10mib.png",
"http": 202,
"status": "ready",
"error_code": null,
"variants": [
"crop",
"optimized",
"thumbnail"
]
},
{
"file": "png-over-10mib.png",
"http": "rejected"
},
{
"file": "png-over-pixels-8001x5000.png",
"http": "rejected"
},
{
"file": "jpeg-over-pixels-10000x5000.jpg",
"http": "rejected"
},
{
"file": "png-truncated.png",
"http": "rejected"
},
{
"file": "png-corrupt-idat.png",
"http": "rejected"
},
{
"file": "jpeg-truncated.jpg",
"http": "rejected"
},
{
"file": "png-zero-width.png",
"http": "rejected"
},
{
"file": "not-an-image.png",
"http": "rejected"
},
{
"file": "gif-declared-as-png.png",
"http": "rejected"
}
]
}
},
{
"name": "crash_commit_publish",
"level": 4,
"window": "after COMMIT, before publish",
"seconds": 9.5,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25d-7d90-757d-a6cf-f374e63cf7cb",
"exit_code": 137,
"after_crash": {
"outbox_published": false,
"status": "queued",
"containers": [
"mtusi2026lab5-relay-1 57ef736182d7 exited Exited (137) 1 second ago"
]
},
"variants": [
{
"pipeline_version": 1,
"name": "crop",
"sha256": "97bf1400b30a28c19420a30161c944f57b5e7d613533b76afe6ab2531cba0143",
"size_bytes": 1820,
"object_key": "variants/01a1b25d-7d90-757d-a6cf-f374e63cf7cb/1/crop-97bf1400b30a28c1.jpg"
},
{
"pipeline_version": 1,
"name": "optimized",
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
"size_bytes": 2462,
"object_key": "variants/01a1b25d-7d90-757d-a6cf-f374e63cf7cb/1/optimized-1090d84ed8411226.webp"
},
{
"pipeline_version": 1,
"name": "thumbnail",
"sha256": "7bc40bf315c8e18e907889b23514d978be213a44223d64b737290188ee808594",
"size_bytes": 4679,
"object_key": "variants/01a1b25d-7d90-757d-a6cf-f374e63cf7cb/1/thumbnail-7bc40bf315c8e18e.jpg"
}
]
}
},
{
"name": "crash_publish_confirm",
"level": 4,
"window": "after publish, before confirm",
"seconds": 9.6,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25d-a31a-7261-975c-7bde40c0e108",
"exit_code": 137,
"after_crash": {
"outbox_published": [
false
],
"queues": {
"attachments.process": [
0,
0
],
"attachments.process.dlq": [
14,
0
]
},
"containers": [
"mtusi2026lab5-relay-1 9f63b40078d5 exited Exited (137) 1 second ago"
]
},
"variants": [
{
"pipeline_version": 1,
"name": "crop",
"sha256": "97bf1400b30a28c19420a30161c944f57b5e7d613533b76afe6ab2531cba0143",
"size_bytes": 1820,
"object_key": "variants/01a1b25d-a31a-7261-975c-7bde40c0e108/1/crop-97bf1400b30a28c1.jpg"
},
{
"pipeline_version": 1,
"name": "optimized",
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
"size_bytes": 2462,
"object_key": "variants/01a1b25d-a31a-7261-975c-7bde40c0e108/1/optimized-1090d84ed8411226.webp"
},
{
"pipeline_version": 1,
"name": "thumbnail",
"sha256": "7bc40bf315c8e18e907889b23514d978be213a44223d64b737290188ee808594",
"size_bytes": 4679,
"object_key": "variants/01a1b25d-a31a-7261-975c-7bde40c0e108/1/thumbnail-7bc40bf315c8e18e.jpg"
}
],
"events": [
"enqueued",
"claimed",
"done",
"duplicate_noop"
]
}
},
{
"name": "crash_after_s3_before_commit",
"level": 4,
"window": "after S3 write, before COMMIT",
"seconds": 12.6,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25d-c77d-705e-b838-9d9ba15fbadf",
"exit_code": 137,
"after_crash": {
"status": "processing",
"variant_rows": 0,
"containers": [
"mtusi2026lab5-worker-1 c74820bbdab3 exited Exited (137) Less than a second ago"
]
},
"variants": [
{
"pipeline_version": 1,
"name": "crop",
"sha256": "97bf1400b30a28c19420a30161c944f57b5e7d613533b76afe6ab2531cba0143",
"size_bytes": 1820,
"object_key": "variants/01a1b25d-c77d-705e-b838-9d9ba15fbadf/1/crop-97bf1400b30a28c1.jpg"
},
{
"pipeline_version": 1,
"name": "optimized",
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
"size_bytes": 2462,
"object_key": "variants/01a1b25d-c77d-705e-b838-9d9ba15fbadf/1/optimized-1090d84ed8411226.webp"
},
{
"pipeline_version": 1,
"name": "thumbnail",
"sha256": "7bc40bf315c8e18e907889b23514d978be213a44223d64b737290188ee808594",
"size_bytes": 4679,
"object_key": "variants/01a1b25d-c77d-705e-b838-9d9ba15fbadf/1/thumbnail-7bc40bf315c8e18e.jpg"
}
]
}
},
{
"name": "crash_after_commit_before_ack",
"level": 4,
"window": "after COMMIT, before ack",
"seconds": 10.3,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25d-f8da-76d9-b714-f7b55947a801",
"exit_code": 137,
"after_crash": {
"status": "ready",
"variants": [
{
"pipeline_version": 1,
"name": "crop",
"sha256": "97bf1400b30a28c19420a30161c944f57b5e7d613533b76afe6ab2531cba0143",
"size_bytes": 1820,
"object_key": "variants/01a1b25d-f8da-76d9-b714-f7b55947a801/1/crop-97bf1400b30a28c1.jpg"
},
{
"pipeline_version": 1,
"name": "optimized",
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
"size_bytes": 2462,
"object_key": "variants/01a1b25d-f8da-76d9-b714-f7b55947a801/1/optimized-1090d84ed8411226.webp"
},
{
"pipeline_version": 1,
"name": "thumbnail",
"sha256": "7bc40bf315c8e18e907889b23514d978be213a44223d64b737290188ee808594",
"size_bytes": 4679,
"object_key": "variants/01a1b25d-f8da-76d9-b714-f7b55947a801/1/thumbnail-7bc40bf315c8e18e.jpg"
}
],
"queues": {
"attachments.process": [
0,
0
],
"attachments.process.dlq": [
14,
0
]
},
"containers": [
"mtusi2026lab5-worker-1 5accc3314905 exited Exited (137) 1 second ago"
]
},
"variants": [
{
"pipeline_version": 1,
"name": "crop",
"sha256": "97bf1400b30a28c19420a30161c944f57b5e7d613533b76afe6ab2531cba0143",
"size_bytes": 1820,
"object_key": "variants/01a1b25d-f8da-76d9-b714-f7b55947a801/1/crop-97bf1400b30a28c1.jpg"
},
{
"pipeline_version": 1,
"name": "optimized",
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
"size_bytes": 2462,
"object_key": "variants/01a1b25d-f8da-76d9-b714-f7b55947a801/1/optimized-1090d84ed8411226.webp"
},
{
"pipeline_version": 1,
"name": "thumbnail",
"sha256": "7bc40bf315c8e18e907889b23514d978be213a44223d64b737290188ee808594",
"size_bytes": 4679,
"object_key": "variants/01a1b25d-f8da-76d9-b714-f7b55947a801/1/thumbnail-7bc40bf315c8e18e.jpg"
}
]
}
},
{
"name": "lease_expiry_fencing",
"level": 4,
"window": "stalled worker, lease expiry",
"seconds": 33.2,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25e-2176-73e5-8d6d-34386191c57a",
"jobs": [
{
"job_id": "01a1b25e-2183-77e4-b40b-4afd30e5e553",
"pipeline_version": 1,
"status": "done",
"attempt": 2
}
],
"events": [
{
"kind": "enqueued",
"attempt": 1
},
{
"kind": "claimed",
"attempt": 1
},
{
"kind": "lease_expired",
"attempt": 2
},
{
"kind": "claimed",
"attempt": 2
},
{
"kind": "done",
"attempt": 2
},
{
"kind": "fenced",
"attempt": 1
}
]
}
},
{
"name": "replay_failed",
"level": 4,
"window": "operator replay",
"seconds": 28.4,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25e-a2f3-754b-982c-49da221caf59",
"replay": {
"result": "replayed",
"attachment_id": "01a1b25e-a2f3-754b-982c-49da221caf59",
"operator": "cli"
},
"replay_of_ready": {
"result": "noop",
"attachment_id": "01a1b25e-a2f3-754b-982c-49da221caf59",
"operator": "cli"
},
"events": [
{
"kind": "enqueued",
"attempt": 1
},
{
"kind": "claimed",
"attempt": 1
},
{
"kind": "retry_scheduled",
"attempt": 2
},
{
"kind": "claimed",
"attempt": 2
},
{
"kind": "retry_scheduled",
"attempt": 3
},
{
"kind": "claimed",
"attempt": 3
},
{
"kind": "retry_scheduled",
"attempt": 4
},
{
"kind": "claimed",
"attempt": 4
},
{
"kind": "retry_scheduled",
"attempt": 5
},
{
"kind": "claimed",
"attempt": 5
},
{
"kind": "failed",
"attempt": 5
},
{
"kind": "replayed",
"attempt": 1
},
{
"kind": "claimed",
"attempt": 1
},
{
"kind": "done",
"attempt": 1
},
{
"kind": "replay_noop",
"attempt": 1
}
]
}
},
{
"name": "malformed_message_dead_lettered",
"level": 4,
"window": "message that is not a job goes to the DLQ",
"seconds": 3.3,
"result": "PASS",
"observed": {
"dead_letters": 1
}
},
{
"name": "worker_limits",
"level": 4,
"window": "render time and memory limits, 40 Mpx in the worker limit",
"seconds": 15.4,
"result": "PASS",
"observed": {
"image": {
"file": "png-at-pixel-limit-8000x5000.png",
"bytes": 116714,
"pixels": 40000000
},
"render_timeout": {
"seconds": 0.5,
"attachment_id": "01a1b25f-1ffa-72fb-8c1c-fca83d40d0fb",
"error_code": "processing_failed",
"worker": "running"
},
"render_memory": {
"mib": 200,
"attachment_id": "01a1b25f-31a6-7720-bd4f-60787194d5e5",
"error_code": "processing_failed",
"worker": "running"
},
"default_limits": {
"attachment_id": "01a1b25f-44b2-755b-a71e-634205be8c09",
"variants": [
"crop",
"optimized",
"thumbnail"
],
"memory_peak_mib": 423.0,
"memory_max_mib": 1024.0
}
}
},
{
"name": "retry_backoff_jitter",
"level": 4,
"window": "backoff with equal jitter between attempts",
"seconds": 18.1,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25f-5abe-7238-b0b2-db991857b384",
"delays": [
{
"attempt": 2,
"delay": 0.722422
},
{
"attempt": 3,
"delay": 1.010937
},
{
"attempt": 4,
"delay": 2.240832
},
{
"attempt": 5,
"delay": 4.845013
}
],
"share_of_ceiling": [
0.722,
0.505,
0.56,
0.606
],
"jobs": [
{
"job_id": "01a1b25f-5ac6-7404-bd51-464f6f4e81f9",
"pipeline_version": 1,
"status": "failed",
"attempt": 5
}
]
}
},
{
"name": "failed_retention",
"level": 4,
"window": "failed staging kept until retention, then replay expires",
"seconds": 21.4,
"result": "PASS",
"observed": {
"attachment_id": "01a1b25f-a149-70cd-8c7f-dfd4ec7c8883",
"staging_before": "kept",
"retention_seconds": 86400,
"aged_only": "01a1b25f-a149-70cd-8c7f-dfd4ec7c8883",
"replay": {
"result": "expired",
"attachment_id": "01a1b25f-a149-70cd-8c7f-dfd4ec7c8883",
"operator": "cli"
}
}
}
],
"result": "PASS",
"finished_at": "2026-11-06T19:40:34.408683Z"
}
@@ -0,0 +1,29 @@
date: 2026-11-06T09:13:49Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ python3 scripts/limits.py
date: 2026-11-06T09:13:49Z commit: 75b93bb
$ docker compose --profile bench --profile tools --profile reconcile config --format json (declared)
service cpus/mem ports secrets volumes networks ro user
---------- ---------- ------------------------------- ------------------------------------------------------------------------------------------------------------------------------- ---------- ---------------------- ----- -----------
api 1/512MiB - cache_url,cursor_secret,database_url,s3_access_key_id,s3_secret_access_key - backend(internal) true image
k6 2/512MiB - - - edge false image
lb 1/128MiB 127.0.0.1:18084,127.0.0.1:24844 - - backend(internal),edge true image
migrate 0.5/256MiB - database_url - backend(internal) false image
postgres 2/1024MiB - postgres_password pgdata backend(internal) false 70:70
reconciler 1/256MiB - database_url,s3_reconciler_access_key_id,s3_reconciler_secret_access_key - backend(internal) true image
s3 1/512MiB - s3_root_password,s3_root_user s3data backend(internal) true image
s3-cli 0.5/64MiB - s3_access_key_id,s3_reconciler_access_key_id,s3_reconciler_secret_access_key,s3_root_password,s3_root_user,s3_secret_access_key - backend(internal) true 65534:65534
s3-init 0.5/64MiB - s3_access_key_id,s3_reconciler_access_key_id,s3_reconciler_secret_access_key,s3_root_password,s3_root_user,s3_secret_access_key - backend(internal) true 65534:65534
valkey 0.5/128MiB - valkey.conf valkeydata backend(internal) false 999:1000
$ docker inspect (running containers: hostname = X-Instance-Id, applied limits)
service hostname cpus memory published
-------- ------------ ---- ------- ---------------------------------------------------
api da922ab2ea09 1 512MiB
lb ea6930f64089 1 128MiB 127.0.0.1:18084->8080/tcp,127.0.0.1:24844->8404/tcp
postgres 3f3a870d89c0 2 1024MiB
s3 5921e788f03d 1 512MiB
valkey 07ea16e2fcfe 0.5 128MiB
PASS: limits, ports, secrets, volumes and networks match the policy
exit_code: 0 elapsed_seconds: 0.308
@@ -0,0 +1,116 @@
date: 2026-11-06T09:16:16Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ make load-evidence
sh scripts/load-evidence.sh
date: 2026-11-06T09:16:17Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082 network: hlpipe-lab4-forward-final-20261106_edge
# make load-evidence (scripts/load-evidence.sh): закрытый контур tests/load.py, 64 потока, 8 с, все записи
# прогона в один новый чат, 3 повтора с паузой 15 с; клиент — одноразовый контейнер в сети <проект>_edge
# стенда (2 CPU, 512 MiB, базовый образ API по digest, tests/, contracts/ и lab.json только для чтения,
# tcp_tw_reuse=1), адрес http://lb:8080. На 4-й секунде — docker stats; после прогона — request.handled реплик.
$ docker ps --format '{{.Names}}' | grep -v '^hlpipe-lab4-forward-final-20261106-' # чужие контейнеры на VM во время серии
$ client() { docker run --rm --name hlpipe-lab4-forward-final-20261106-load-client --network hlpipe-lab4-forward-final-20261106_edge --cpus 2 --memory 512m --sysctl net.ipv4.tcp_tw_reuse=1 -v "$PWD/tests:/w/tests:ro" -v "$PWD/contracts:/w/contracts:ro" -v "$PWD/lab.json:/w/lab.json:ro" -v "$PWD/evidence/forward-final-2026-11-06/load:/out" python:3.14-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d python /w/tests/load.py "$@"; }
$ client --base-url http://lb:8080 --duration 8 --concurrency 64 --output /out/run1.json
exit 0
{
"lab": 4,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 8.0,
"elapsed_seconds": 8.238,
"concurrency": 64,
"successful_requests": 11768,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 1428.577,
"successful_latency_ms": {
"p50": 40.163,
"p95": 100.062,
"p99": 141.558
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
$ docker stats --no-stream # 4-я секунда прогона: контейнер CPU% память
api-1 93.26% 271.2MiB / 512MiB
api-2 89.65% 307.4MiB / 512MiB
lb-1 46.78% 30.14MiB / 128MiB
load-client 60.53% 83.66MiB / 512MiB
postgres-1 157.07% 151.1MiB / 1GiB
s3-1 0.76% 69.52MiB / 512MiB
valkey-1 3.81% 13.9MiB / 128MiB
$ docker compose logs --since 2026-11-06T09:16:17Z api | request.handled: статус метод маршрут число
200 GET /health/live 1
200 GET /health/ready 22
201 POST /api/v1/auth/sessions 3
201 POST /api/v1/chats 1
201 POST /api/v1/chats/{chat_id}/messages 11768
201 POST /api/v1/users 3
$ client --base-url http://lb:8080 --duration 8 --concurrency 64 --output /out/run2.json
exit 0
{
"lab": 4,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 8.0,
"elapsed_seconds": 8.229,
"concurrency": 64,
"successful_requests": 11984,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 1456.338,
"successful_latency_ms": {
"p50": 37.442,
"p95": 98.948,
"p99": 134.678
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
$ docker stats --no-stream # 4-я секунда прогона: контейнер CPU% память
api-1 90.89% 272.5MiB / 512MiB
api-2 75.30% 310.1MiB / 512MiB
lb-1 39.94% 30.58MiB / 128MiB
load-client 46.50% 83.65MiB / 512MiB
postgres-1 121.64% 158.2MiB / 1GiB
s3-1 0.77% 69.37MiB / 512MiB
valkey-1 3.02% 13.87MiB / 128MiB
$ docker compose logs --since 2026-11-06T09:16:41Z api | request.handled: статус метод маршрут число
200 GET /health/live 1
200 GET /health/ready 23
201 POST /api/v1/auth/sessions 3
201 POST /api/v1/chats 1
201 POST /api/v1/chats/{chat_id}/messages 11984
201 POST /api/v1/users 3
$ client --base-url http://lb:8080 --duration 8 --concurrency 64 --output /out/run3.json
exit 0
{
"lab": 4,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 8.0,
"elapsed_seconds": 8.21,
"concurrency": 64,
"successful_requests": 12555,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 1529.32,
"successful_latency_ms": {
"p50": 33.478,
"p95": 98.475,
"p99": 138.028
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
$ docker stats --no-stream # 4-я секунда прогона: контейнер CPU% память
api-1 100.60% 273.6MiB / 512MiB
api-2 99.12% 310.2MiB / 512MiB
lb-1 58.14% 30.39MiB / 128MiB
load-client 66.66% 83.66MiB / 512MiB
postgres-1 168.89% 167.2MiB / 1GiB
s3-1 0.80% 71.19MiB / 512MiB
valkey-1 4.31% 13.5MiB / 128MiB
$ docker compose logs --since 2026-11-06T09:17:05Z api | request.handled: статус метод маршрут число
200 GET /health/live 1
200 GET /health/ready 24
201 POST /api/v1/auth/sessions 3
201 POST /api/v1/chats 1
201 POST /api/v1/chats/{chat_id}/messages 12555
201 POST /api/v1/users 3
$ docker compose exec -T postgres psql -c 'SELECT count(*) FROM messages'
36448
exit_code: 0 elapsed_seconds: 57.764
+111
View File
@@ -0,0 +1,111 @@
date: 2026-11-06T09:16:17Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082 network: hlpipe-lab4-forward-final-20261106_edge
# make load-evidence (scripts/load-evidence.sh): закрытый контур tests/load.py, 64 потока, 8 с, все записи
# прогона в один новый чат, 3 повтора с паузой 15 с; клиент — одноразовый контейнер в сети <проект>_edge
# стенда (2 CPU, 512 MiB, базовый образ API по digest, tests/, contracts/ и lab.json только для чтения,
# tcp_tw_reuse=1), адрес http://lb:8080. На 4-й секунде — docker stats; после прогона — request.handled реплик.
$ docker ps --format '{{.Names}}' | grep -v '^hlpipe-lab4-forward-final-20261106-' # чужие контейнеры на VM во время серии
$ client() { docker run --rm --name hlpipe-lab4-forward-final-20261106-load-client --network hlpipe-lab4-forward-final-20261106_edge --cpus 2 --memory 512m --sysctl net.ipv4.tcp_tw_reuse=1 -v "$PWD/tests:/w/tests:ro" -v "$PWD/contracts:/w/contracts:ro" -v "$PWD/lab.json:/w/lab.json:ro" -v "$PWD/evidence/forward-final-2026-11-06/load:/out" python:3.14-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d python /w/tests/load.py "$@"; }
$ client --base-url http://lb:8080 --duration 8 --concurrency 64 --output /out/run1.json
exit 0
{
"lab": 4,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 8.0,
"elapsed_seconds": 8.238,
"concurrency": 64,
"successful_requests": 11768,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 1428.577,
"successful_latency_ms": {
"p50": 40.163,
"p95": 100.062,
"p99": 141.558
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
$ docker stats --no-stream # 4-я секунда прогона: контейнер CPU% память
api-1 93.26% 271.2MiB / 512MiB
api-2 89.65% 307.4MiB / 512MiB
lb-1 46.78% 30.14MiB / 128MiB
load-client 60.53% 83.66MiB / 512MiB
postgres-1 157.07% 151.1MiB / 1GiB
s3-1 0.76% 69.52MiB / 512MiB
valkey-1 3.81% 13.9MiB / 128MiB
$ docker compose logs --since 2026-11-06T09:16:17Z api | request.handled: статус метод маршрут число
200 GET /health/live 1
200 GET /health/ready 22
201 POST /api/v1/auth/sessions 3
201 POST /api/v1/chats 1
201 POST /api/v1/chats/{chat_id}/messages 11768
201 POST /api/v1/users 3
$ client --base-url http://lb:8080 --duration 8 --concurrency 64 --output /out/run2.json
exit 0
{
"lab": 4,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 8.0,
"elapsed_seconds": 8.229,
"concurrency": 64,
"successful_requests": 11984,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 1456.338,
"successful_latency_ms": {
"p50": 37.442,
"p95": 98.948,
"p99": 134.678
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
$ docker stats --no-stream # 4-я секунда прогона: контейнер CPU% память
api-1 90.89% 272.5MiB / 512MiB
api-2 75.30% 310.1MiB / 512MiB
lb-1 39.94% 30.58MiB / 128MiB
load-client 46.50% 83.65MiB / 512MiB
postgres-1 121.64% 158.2MiB / 1GiB
s3-1 0.77% 69.37MiB / 512MiB
valkey-1 3.02% 13.87MiB / 128MiB
$ docker compose logs --since 2026-11-06T09:16:41Z api | request.handled: статус метод маршрут число
200 GET /health/live 1
200 GET /health/ready 23
201 POST /api/v1/auth/sessions 3
201 POST /api/v1/chats 1
201 POST /api/v1/chats/{chat_id}/messages 11984
201 POST /api/v1/users 3
$ client --base-url http://lb:8080 --duration 8 --concurrency 64 --output /out/run3.json
exit 0
{
"lab": 4,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 8.0,
"elapsed_seconds": 8.21,
"concurrency": 64,
"successful_requests": 12555,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 1529.32,
"successful_latency_ms": {
"p50": 33.478,
"p95": 98.475,
"p99": 138.028
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
$ docker stats --no-stream # 4-я секунда прогона: контейнер CPU% память
api-1 100.60% 273.6MiB / 512MiB
api-2 99.12% 310.2MiB / 512MiB
lb-1 58.14% 30.39MiB / 128MiB
load-client 66.66% 83.66MiB / 512MiB
postgres-1 168.89% 167.2MiB / 1GiB
s3-1 0.80% 71.19MiB / 512MiB
valkey-1 4.31% 13.5MiB / 128MiB
$ docker compose logs --since 2026-11-06T09:17:05Z api | request.handled: статус метод маршрут число
200 GET /health/live 1
200 GET /health/ready 24
201 POST /api/v1/auth/sessions 3
201 POST /api/v1/chats 1
201 POST /api/v1/chats/{chat_id}/messages 12555
201 POST /api/v1/users 3
$ docker compose exec -T postgres psql -c 'SELECT count(*) FROM messages'
36448
@@ -0,0 +1,17 @@
{
"lab": 4,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 8.0,
"elapsed_seconds": 8.238,
"concurrency": 64,
"successful_requests": 11768,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 1428.577,
"successful_latency_ms": {
"p50": 40.163,
"p95": 100.062,
"p99": 141.558
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
@@ -0,0 +1,17 @@
{
"lab": 4,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 8.0,
"elapsed_seconds": 8.229,
"concurrency": 64,
"successful_requests": 11984,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 1456.338,
"successful_latency_ms": {
"p50": 37.442,
"p95": 98.948,
"p99": 134.678
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
@@ -0,0 +1,17 @@
{
"lab": 4,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 8.0,
"elapsed_seconds": 8.21,
"concurrency": 64,
"successful_requests": 12555,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 1529.32,
"successful_latency_ms": {
"p50": 33.478,
"p95": 98.475,
"p99": 138.028
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
@@ -0,0 +1,41 @@
date: 2026-11-06T09:18:23Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ make down
docker compose --profile bench --profile tools --profile reconcile down
Container hlpipe-lab4-forward-final-20261106-api-2 Stopping
Container hlpipe-lab4-forward-final-20261106-lb-1 Stopping
Container hlpipe-lab4-forward-final-20261106-api-1 Stopping
Container hlpipe-lab4-forward-final-20261106-lb-1 Stopped
Container hlpipe-lab4-forward-final-20261106-lb-1 Removing
Container hlpipe-lab4-forward-final-20261106-lb-1 Removed
Container hlpipe-lab4-forward-final-20261106-api-1 Stopped
Container hlpipe-lab4-forward-final-20261106-api-1 Removing
Container hlpipe-lab4-forward-final-20261106-api-1 Removed
Container hlpipe-lab4-forward-final-20261106-api-2 Stopped
Container hlpipe-lab4-forward-final-20261106-api-2 Removing
Container hlpipe-lab4-forward-final-20261106-api-2 Removed
Container hlpipe-lab4-forward-final-20261106-s3-init-1 Stopping
Container hlpipe-lab4-forward-final-20261106-migrate-1 Stopping
Container hlpipe-lab4-forward-final-20261106-valkey-1 Stopping
Container hlpipe-lab4-forward-final-20261106-s3-init-1 Stopped
Container hlpipe-lab4-forward-final-20261106-s3-init-1 Removing
Container hlpipe-lab4-forward-final-20261106-migrate-1 Stopped
Container hlpipe-lab4-forward-final-20261106-migrate-1 Removing
Container hlpipe-lab4-forward-final-20261106-s3-init-1 Removed
Container hlpipe-lab4-forward-final-20261106-s3-1 Stopping
Container hlpipe-lab4-forward-final-20261106-migrate-1 Removed
Container hlpipe-lab4-forward-final-20261106-postgres-1 Stopping
Container hlpipe-lab4-forward-final-20261106-valkey-1 Stopped
Container hlpipe-lab4-forward-final-20261106-valkey-1 Removing
Container hlpipe-lab4-forward-final-20261106-valkey-1 Removed
Container hlpipe-lab4-forward-final-20261106-s3-1 Stopped
Container hlpipe-lab4-forward-final-20261106-s3-1 Removing
Container hlpipe-lab4-forward-final-20261106-postgres-1 Stopped
Container hlpipe-lab4-forward-final-20261106-postgres-1 Removing
Container hlpipe-lab4-forward-final-20261106-s3-1 Removed
Container hlpipe-lab4-forward-final-20261106-postgres-1 Removed
Network hlpipe-lab4-forward-final-20261106_edge Removing
Network hlpipe-lab4-forward-final-20261106_backend Removing
Network hlpipe-lab4-forward-final-20261106_edge Removed
Network hlpipe-lab4-forward-final-20261106_backend Removed
exit_code: 0 elapsed_seconds: 3.283
@@ -0,0 +1,72 @@
{
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"load_rps": {
"all": [
1428.577,
1456.338,
1529.32
],
"median": 1456.338,
"min": 1428.577,
"max": 1529.32
},
"load_p95_ms": {
"all": [
100.062,
98.948,
98.475
],
"median": 98.948,
"min": 98.475,
"max": 100.062
},
"load_failed": 0,
"memory_statuses": [
{
"201": 80
},
{
"201": 80
},
{
"201": 78,
"503": 2
}
],
"body_bytes": [
10485256,
10485256,
10485256
],
"api_peak_mib": {
"all": [
456.2,
438.1,
450.4
],
"median": 450.4,
"min": 438.1,
"max": 456.2
},
"lb_peak_mib": {
"all": [
31.8,
28.5,
29.1
],
"median": 29.1,
"min": 28.5,
"max": 31.8
},
"upload_p95_ms": {
"all": [
3641.3,
4755.0,
8091.8
],
"median": 4755.0,
"min": 3641.3,
"max": 8091.8
},
"oom": 0
}
@@ -0,0 +1,87 @@
date: 2026-11-06T09:21:03Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {}
$ python3 -c 'import json,statistics,subprocess
from pathlib import Path
root=Path("evidence/forward-final-2026-11-06")
loads=[json.loads(p.read_text()) for p in sorted((root/"load").glob("run*.json"))]
memory=[json.loads(p.read_text()) for p in sorted((root/"memory").glob("run*/slots*.json"))]
assert len(loads)==len(memory)==3
assert all(r["failed_requests"]==0 for r in loads)
assert all(r["count"]==80 and r["concurrency"]==40 and r["upload_concurrency"]==3 for r in memory)
def stats(values):return {"all":values,"median":statistics.median(values),"min":min(values),"max":max(values)}
result={"commit":subprocess.check_output(["git","rev-parse","HEAD"],text=True).strip(),"load_rps":stats([r["successful_rps"] for r in loads]),"load_p95_ms":stats([r["successful_latency_ms"]["p95"] for r in loads]),"load_failed":sum(r["failed_requests"] for r in loads),"memory_statuses":[r["status_codes"] for r in memory],"body_bytes":[r["body_bytes"] for r in memory],"api_peak_mib":stats([max(v["cgroup_memory_peak_mib"] for v in r["memory"].values()) for r in memory]),"lb_peak_mib":stats([r["lb"]["cgroup_memory_peak_mib"] for r in memory]),"upload_p95_ms":stats([r["latency_ms"]["p95"] for r in memory]),"oom":sum(sum(v["oom_kill"] for v in r["memory"].values())+r["lb"]["oom_kill"] for r in memory)}
with (root/"measurement-summary.json").open("x") as stream:json.dump(result,stream,indent=2);stream.write("\n")
print(json.dumps(result,indent=2))'
{
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"load_rps": {
"all": [
1428.577,
1456.338,
1529.32
],
"median": 1456.338,
"min": 1428.577,
"max": 1529.32
},
"load_p95_ms": {
"all": [
100.062,
98.948,
98.475
],
"median": 98.948,
"min": 98.475,
"max": 100.062
},
"load_failed": 0,
"memory_statuses": [
{
"201": 80
},
{
"201": 80
},
{
"201": 78,
"503": 2
}
],
"body_bytes": [
10485256,
10485256,
10485256
],
"api_peak_mib": {
"all": [
456.2,
438.1,
450.4
],
"median": 450.4,
"min": 438.1,
"max": 456.2
},
"lb_peak_mib": {
"all": [
31.8,
28.5,
29.1
],
"median": 29.1,
"min": 28.5,
"max": 31.8
},
"upload_p95_ms": {
"all": [
3641.3,
4755.0,
8091.8
],
"median": 4755.0,
"min": 3641.3,
"max": 8091.8
},
"oom": 0
}
exit_code: 0 elapsed_seconds: 0.048
@@ -0,0 +1,7 @@
date: 2026-11-06T09:17:14Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ python3 scripts/upload_memory.py --base-url http://127.0.0.1:18084 --slots 3 --sizes 10485760 --levels 40 --out evidence/forward-final-2026-11-06/memory/run1
# 2026-11-06T09:17:14Z commit 75b93bbba5f29575d3fca1d013cc7e0770d88082; api x2: 1 CPU, 512 MiB, 2 workers; MALLOC_MMAP_THRESHOLD_=131072; 2 uploads per client; peaks from cgroup memory.peak, MiB
slots size conc codes p50_ms p95_ms api_idle api_peak api_oom lb_peak lb_oom
3 10.0M 40 201x80 2587.5 3641.3 233.2 456.2 0 31.8 0
exit_code: 0 elapsed_seconds: 20.084
@@ -0,0 +1,7 @@
date: 2026-11-06T09:17:34Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ python3 scripts/upload_memory.py --base-url http://127.0.0.1:18084 --slots 3 --sizes 10485760 --levels 40 --out evidence/forward-final-2026-11-06/memory/run2
# 2026-11-06T09:17:34Z commit 75b93bbba5f29575d3fca1d013cc7e0770d88082; api x2: 1 CPU, 512 MiB, 2 workers; MALLOC_MMAP_THRESHOLD_=131072; 2 uploads per client; peaks from cgroup memory.peak, MiB
slots size conc codes p50_ms p95_ms api_idle api_peak api_oom lb_peak lb_oom
3 10.0M 40 201x80 2770.4 4755.0 231.3 438.1 0 28.5 0
exit_code: 0 elapsed_seconds: 21.500
@@ -0,0 +1,7 @@
date: 2026-11-06T09:17:56Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ python3 scripts/upload_memory.py --base-url http://127.0.0.1:18084 --slots 3 --sizes 10485760 --levels 40 --out evidence/forward-final-2026-11-06/memory/run3
# 2026-11-06T09:17:56Z commit 75b93bbba5f29575d3fca1d013cc7e0770d88082; api x2: 1 CPU, 512 MiB, 2 workers; MALLOC_MMAP_THRESHOLD_=131072; 2 uploads per client; peaks from cgroup memory.peak, MiB
slots size conc codes p50_ms p95_ms api_idle api_peak api_oom lb_peak lb_oom
3 10.0M 40 201x78,503x2 3560.9 8091.8 231.7 450.4 0 29.1 0
exit_code: 0 elapsed_seconds: 23.514
@@ -0,0 +1,40 @@
{
"date": "2026-11-06T09:17:21Z",
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"upload_concurrency": 3,
"mode": "http",
"count": 80,
"concurrency": 40,
"body_bytes": 10485256,
"status_codes": {
"201": 80
},
"instances": 2,
"linked_in_messages": 0,
"elapsed_seconds": 6.143,
"successful_rps": 13.02,
"latency_ms": {
"p50": 2587.5,
"p95": 3641.3,
"p99": 4322.0,
"max": 4322.0
},
"memory": {
"35b198e7b5ca": {
"idle_mib": 230.7,
"docker_stats_peak_mib": 409.6,
"cgroup_memory_peak_mib": 424.4,
"oom_kill": 0
},
"93b12ae1c127": {
"idle_mib": 233.2,
"docker_stats_peak_mib": 419.5,
"cgroup_memory_peak_mib": 456.2,
"oom_kill": 0
}
},
"lb": {
"cgroup_memory_peak_mib": 31.8,
"oom_kill": 0
}
}
@@ -0,0 +1,3 @@
# 2026-11-06T09:17:14Z commit 75b93bbba5f29575d3fca1d013cc7e0770d88082; api x2: 1 CPU, 512 MiB, 2 workers; MALLOC_MMAP_THRESHOLD_=131072; 2 uploads per client; peaks from cgroup memory.peak, MiB
slots size conc codes p50_ms p95_ms api_idle api_peak api_oom lb_peak lb_oom
3 10.0M 40 201x80 2587.5 3641.3 233.2 456.2 0 31.8 0
@@ -0,0 +1,40 @@
{
"date": "2026-11-06T09:17:40Z",
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"upload_concurrency": 3,
"mode": "http",
"count": 80,
"concurrency": 40,
"body_bytes": 10485256,
"status_codes": {
"201": 80
},
"instances": 2,
"linked_in_messages": 0,
"elapsed_seconds": 8.053,
"successful_rps": 9.93,
"latency_ms": {
"p50": 2770.4,
"p95": 4755.0,
"p99": 5507.3,
"max": 5507.3
},
"memory": {
"5df14feadc75": {
"idle_mib": 230.1,
"docker_stats_peak_mib": 411.6,
"cgroup_memory_peak_mib": 438.1,
"oom_kill": 0
},
"806f59cf0d4c": {
"idle_mib": 231.3,
"docker_stats_peak_mib": 401.0,
"cgroup_memory_peak_mib": 425.7,
"oom_kill": 0
}
},
"lb": {
"cgroup_memory_peak_mib": 28.5,
"oom_kill": 0
}
}
@@ -0,0 +1,3 @@
# 2026-11-06T09:17:34Z commit 75b93bbba5f29575d3fca1d013cc7e0770d88082; api x2: 1 CPU, 512 MiB, 2 workers; MALLOC_MMAP_THRESHOLD_=131072; 2 uploads per client; peaks from cgroup memory.peak, MiB
slots size conc codes p50_ms p95_ms api_idle api_peak api_oom lb_peak lb_oom
3 10.0M 40 201x80 2770.4 4755.0 231.3 438.1 0 28.5 0
@@ -0,0 +1,41 @@
{
"date": "2026-11-06T09:18:02Z",
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"upload_concurrency": 3,
"mode": "http",
"count": 80,
"concurrency": 40,
"body_bytes": 10485256,
"status_codes": {
"201": 78,
"503": 2
},
"instances": 2,
"linked_in_messages": 0,
"elapsed_seconds": 9.545,
"successful_rps": 8.17,
"latency_ms": {
"p50": 3560.9,
"p95": 8091.8,
"p99": 8772.2,
"max": 8772.2
},
"memory": {
"798d7474c368": {
"idle_mib": 231.7,
"docker_stats_peak_mib": 428.2,
"cgroup_memory_peak_mib": 450.4,
"oom_kill": 0
},
"0b9a4f6359fb": {
"idle_mib": 179.4,
"docker_stats_peak_mib": 410.0,
"cgroup_memory_peak_mib": 430.7,
"oom_kill": 0
}
},
"lb": {
"cgroup_memory_peak_mib": 29.1,
"oom_kill": 0
}
}
@@ -0,0 +1,3 @@
# 2026-11-06T09:17:56Z commit 75b93bbba5f29575d3fca1d013cc7e0770d88082; api x2: 1 CPU, 512 MiB, 2 workers; MALLOC_MMAP_THRESHOLD_=131072; 2 uploads per client; peaks from cgroup memory.peak, MiB
slots size conc codes p50_ms p95_ms api_idle api_peak api_oom lb_peak lb_oom
3 10.0M 40 201x78,503x2 3560.9 8091.8 231.7 450.4 0 29.1 0
@@ -1,31 +1,31 @@
date: 2026-11-06T19:34:10Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
$ python3 student-tests/tools/forward_network.py
date: 2026-11-06T09:10:41Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ .venv/bin/python student-tests/tools/forward_network.py
{
"checks": [
{
"case": "non_ascii_basic",
"raw_hex": "42617369632080",
"status": 401,
"instance": "9aa2e31be8d1"
"instance": "d4c8d53d7433"
},
{
"case": "non_ascii_basic",
"raw_hex": "426173696320ff",
"status": 401,
"instance": "05aaa8c023d0"
"instance": "da922ab2ea09"
},
{
"case": "non_ascii_basic",
"raw_hex": "426173696320c3a9",
"status": 401,
"instance": "9aa2e31be8d1"
"instance": "d4c8d53d7433"
},
{
"case": "non_ascii_basic",
"raw_hex": "42617369632059577870593255366332566a636d5630ff",
"status": 401,
"instance": "05aaa8c023d0"
"instance": "da922ab2ea09"
},
{
"case": "nul_basic_display_title",
@@ -36,7 +36,7 @@ $ python3 student-tests/tools/forward_network.py
201,
400
],
"instance": "9aa2e31be8d1"
"instance": "d4c8d53d7433"
},
{
"case": "nul_basic_display_title",
@@ -47,7 +47,7 @@ $ python3 student-tests/tools/forward_network.py
201,
400
],
"instance": "05aaa8c023d0"
"instance": "da922ab2ea09"
},
{
"case": "nul_basic_display_title",
@@ -58,7 +58,7 @@ $ python3 student-tests/tools/forward_network.py
201,
400
],
"instance": "9aa2e31be8d1"
"instance": "d4c8d53d7433"
},
{
"case": "nul_basic_display_title",
@@ -69,14 +69,14 @@ $ python3 student-tests/tools/forward_network.py
201,
400
],
"instance": "05aaa8c023d0"
"instance": "da922ab2ea09"
},
{
"case": "nul_message_corrected_retry",
"position": "'\\x00'",
"instances": [
"05aaa8c023d0",
"9aa2e31be8d1"
"da922ab2ea09",
"d4c8d53d7433"
],
"status": [
400,
@@ -89,8 +89,8 @@ $ python3 student-tests/tools/forward_network.py
"case": "nul_message_corrected_retry",
"position": "'\\x00abc'",
"instances": [
"9aa2e31be8d1",
"05aaa8c023d0"
"d4c8d53d7433",
"da922ab2ea09"
],
"status": [
400,
@@ -103,8 +103,8 @@ $ python3 student-tests/tools/forward_network.py
"case": "nul_message_corrected_retry",
"position": "'abc\\x00def'",
"instances": [
"05aaa8c023d0",
"9aa2e31be8d1"
"da922ab2ea09",
"d4c8d53d7433"
],
"status": [
400,
@@ -117,8 +117,8 @@ $ python3 student-tests/tools/forward_network.py
"case": "nul_message_corrected_retry",
"position": "'abc\\x00'",
"instances": [
"9aa2e31be8d1",
"05aaa8c023d0"
"d4c8d53d7433",
"da922ab2ea09"
],
"status": [
400,
@@ -146,9 +146,9 @@ $ python3 student-tests/tools/forward_network.py
}
],
"instances": [
"05aaa8c023d0",
"9aa2e31be8d1"
"d4c8d53d7433",
"da922ab2ea09"
],
"pass": true
}
exit_code: 0 elapsed_seconds: 0.309
exit_code: 0 elapsed_seconds: 0.403
@@ -1,7 +1,17 @@
date: 2026-11-06T19:30:50Z commit: f88e9ba43cdfd7eb6a5a7ae5feb4247b4e820071
date: 2026-11-06T09:07:00Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"NO_PROXY": "localhost,127.0.0.1,::1"}
$ make student-test
.venv/bin/pytest
$ sh -c 'make check && make validate && make lint && make student-test'
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
.venv/bin/ruff check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
All checks passed!
.venv/bin/ruff format --check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
163 files already formatted
.venv/bin/ty check src student-tests alembic
All checks passed!
.venv/bin/pytest
============================= test session starts ==============================
platform darwin -- Python 3.14.5, pytest-9.1.1, pluggy-1.6.0
rootdir: <repo>
@@ -9,60 +19,46 @@ configfile: pyproject.toml
testpaths: student-tests
plugins: asyncio-1.4.0, anyio-4.15.1
asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function
collected 839 items / 19 deselected / 820 selected
collected 511 items / 19 deselected / 492 selected
student-tests/adapters/test_rabbitmq.py .... [ 0%]
student-tests/adapters/test_s3_storage.py ... [ 0%]
student-tests/api/test_access.py ......... [ 1%]
student-tests/api/test_attachments.py .................................. [ 6%]
...... [ 6%]
student-tests/api/test_bounded_contexts.py .................... [ 9%]
student-tests/api/test_cache.py ............ [ 10%]
student-tests/api/test_concurrency.py .... [ 11%]
student-tests/api/test_consistency.py ........ [ 12%]
student-tests/api/test_drain.py .. [ 12%]
student-tests/api/test_events.py ...... [ 13%]
student-tests/api/test_idempotency.py ............... [ 15%]
student-tests/api/test_instance.py .... [ 15%]
student-tests/api/test_job_returning.py . [ 15%]
student-tests/api/test_message_attachments.py ............. [ 17%]
student-tests/api/test_migrations.py ................................... [ 21%]
. [ 21%]
student-tests/api/test_negative.py ..................................... [ 26%]
[ 26%]
student-tests/api/test_nul_validation.py ................. [ 28%]
student-tests/api/test_operability.py .............. [ 29%]
student-tests/api/test_pagination.py .................. [ 32%]
student-tests/api/test_pipeline.py ............. [ 33%]
student-tests/api/test_pool.py ............ [ 35%]
student-tests/api/test_reconciler.py ........... [ 36%]
student-tests/api/test_recovery.py ............ [ 37%]
student-tests/api/test_sessions.py ...................... [ 40%]
student-tests/api/test_timeout.py ........ [ 41%]
student-tests/api/test_upload_consistency.py ......... [ 42%]
student-tests/api/test_versioned_pipeline.py ........... [ 44%]
student-tests/api/test_wire_format.py .. [ 44%]
student-tests/unit/test_attachments_domain.py .......................... [ 47%]
. [ 47%]
student-tests/unit/test_authentication.py ............................. [ 51%]
student-tests/unit/test_cursor.py ........... [ 52%]
student-tests/unit/test_domain.py ...................................... [ 57%]
.. [ 57%]
student-tests/unit/test_haproxy_errors.py ............... [ 59%]
student-tests/unit/test_image_inspection.py ............................ [ 62%]
........................................................................ [ 71%]
........................................................................ [ 80%]
..................................................... [ 86%]
student-tests/unit/test_nul_inputs.py ...................... [ 89%]
student-tests/unit/test_pipeline_domain.py ....................... [ 92%]
student-tests/unit/test_png_upload.py .. [ 92%]
student-tests/unit/test_probe.py .............. [ 94%]
student-tests/unit/test_reconcile_measurements.py ...... [ 94%]
student-tests/unit/test_render_pool.py .....s. [ 95%]
student-tests/unit/test_renderer.py .................... [ 98%]
student-tests/unit/test_scaling.py ..... [ 98%]
student-tests/api/test_access.py ......... [ 2%]
student-tests/api/test_attachments.py .................................. [ 9%]
.... [ 10%]
student-tests/api/test_bounded_contexts.py ................... [ 14%]
student-tests/api/test_cache.py ............ [ 16%]
student-tests/api/test_concurrency.py .... [ 17%]
student-tests/api/test_consistency.py ........ [ 18%]
student-tests/api/test_drain.py .. [ 19%]
student-tests/api/test_events.py ...... [ 20%]
student-tests/api/test_idempotency.py ............... [ 23%]
student-tests/api/test_instance.py .... [ 24%]
student-tests/api/test_message_attachments.py ........... [ 26%]
student-tests/api/test_migrations.py ................................ [ 33%]
student-tests/api/test_negative.py ..................................... [ 40%]
[ 40%]
student-tests/api/test_nul_validation.py ................. [ 44%]
student-tests/api/test_operability.py .............. [ 46%]
student-tests/api/test_pagination.py .................. [ 50%]
student-tests/api/test_pool.py ............ [ 53%]
student-tests/api/test_reconciler.py .......... [ 55%]
student-tests/api/test_sessions.py ...................... [ 59%]
student-tests/api/test_timeout.py ........ [ 61%]
student-tests/api/test_upload_consistency.py ......... [ 63%]
student-tests/api/test_wire_format.py .. [ 63%]
student-tests/unit/test_attachments_domain.py .......................... [ 68%]
. [ 68%]
student-tests/unit/test_authentication.py ............................. [ 74%]
student-tests/unit/test_cursor.py ........... [ 77%]
student-tests/unit/test_domain.py ...................................... [ 84%]
.. [ 85%]
student-tests/unit/test_haproxy_errors.py ............... [ 88%]
student-tests/unit/test_nul_inputs.py ...................... [ 92%]
student-tests/unit/test_probe.py .............. [ 95%]
student-tests/unit/test_reconcile_measurements.py ...... [ 96%]
student-tests/unit/test_scaling.py ..... [ 97%]
student-tests/unit/test_session_cache.py .......... [ 99%]
student-tests/unit/test_timeouts.py . [100%]
========== 819 passed, 1 skipped, 19 deselected in 150.77s (0:02:30) ===========
exit_code: 0 elapsed_seconds: 152.249
================ 492 passed, 19 deselected in 88.06s (0:01:28) =================
exit_code: 0 elapsed_seconds: 90.288
@@ -0,0 +1,36 @@
date: 2026-11-06T09:06:38Z commit: f0fc084fbbc6a6084ac9526c50fcee45b2c9a277
environment: {"NO_PROXY": "localhost,127.0.0.1,::1"}
$ sh -c 'make check && make validate && make lint && make student-test'
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
.venv/bin/ruff check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
All checks passed!
.venv/bin/ruff format --check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
163 files already formatted
.venv/bin/ty check src student-tests alembic
error[invalid-argument-type]: Argument to `HTTPConnection.__init__` is incorrect
--> student-tests/tools/forward_network.py:16:39
|
16 | conn = http.client.HTTPConnection(base.hostname, base.port, timeout=12)
| ^^^^^^^^^^^^^ Expected `str`, found `str | None`
info: element `None` of union `str | None` is not assignable to `str`
info: Method defined here
--> stdlib/http/client.pyi:336:13
|
336 | def __init__(
| ^^^^^^^^
337 | self,
338 | host: str,
| --------- Parameter declared here
error[not-subscriptable]: Cannot subscript object of type `None` with no `__getitem__` method
--> student-tests/tools/forward_network.py:28:16
|
28 | assert result["error"]["request_id"] == request_id
| ^^^^^^^^^^^^^^^
Found 2 diagnostics
make: *** [lint] Error 1
exit_code: 2 elapsed_seconds: 0.678
@@ -0,0 +1,7 @@
date: 2026-11-06T09:32:35Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {}
$ openspec archive forward-lab3-final-review-fixes --yes --skip-specs
Task status: ✓ Complete
Skipping spec updates (--skip-specs flag provided).
Change 'forward-lab3-final-review-fixes' archived as '2026-11-06-forward-lab3-final-review-fixes'.
exit_code: 0 elapsed_seconds: 0.776
@@ -0,0 +1,17 @@
date: 2026-11-06T09:18:19Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ sh -c 'uptime; docker ps --format "{{.Names}} {{.Status}}"; docker stats --no-stream --format "{{.Name}} {{.CPUPerc}} {{.MemUsage}}"'
12:18 up 37 days, 11:30, 6 users, load averages: 4.69 4.19 4.16
hlpipe-lab4-forward-final-20261106-api-1 Up 2 seconds (healthy)
hlpipe-lab4-forward-final-20261106-api-2 Up 2 seconds (healthy)
hlpipe-lab4-forward-final-20261106-lb-1 Up 2 seconds (healthy)
hlpipe-lab4-forward-final-20261106-postgres-1 Up 5 minutes (healthy)
hlpipe-lab4-forward-final-20261106-s3-1 Up 4 minutes (healthy)
hlpipe-lab4-forward-final-20261106-valkey-1 Up 5 minutes (healthy)
hlpipe-lab4-forward-final-20261106-api-1 0.49% 227.9MiB / 512MiB
hlpipe-lab4-forward-final-20261106-api-2 0.83% 227.9MiB / 512MiB
hlpipe-lab4-forward-final-20261106-lb-1 1.16% 15.97MiB / 128MiB
hlpipe-lab4-forward-final-20261106-postgres-1 2.18% 59.24MiB / 1GiB
hlpipe-lab4-forward-final-20261106-s3-1 1.32% 297.5MiB / 512MiB
hlpipe-lab4-forward-final-20261106-valkey-1 0.19% 13.54MiB / 128MiB
exit_code: 0 elapsed_seconds: 2.646
@@ -0,0 +1,18 @@
date: 2026-11-06T09:16:14Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ sh -c 'docker info --format "cpus={{.NCPU}} memory={{.MemTotal}}"; uptime; docker ps --format "{{.Names}} {{.Status}}"; docker stats --no-stream --format "{{.Name}} {{.CPUPerc}} {{.MemUsage}}"'
cpus=16 memory=8217190400
12:16 up 37 days, 11:28, 6 users, load averages: 3.42 4.16 4.16
hlpipe-lab4-forward-final-20261106-api-1 Up About a minute (healthy)
hlpipe-lab4-forward-final-20261106-api-2 Up 3 minutes (healthy)
hlpipe-lab4-forward-final-20261106-postgres-1 Up 3 minutes (healthy)
hlpipe-lab4-forward-final-20261106-lb-1 Up 3 minutes (healthy)
hlpipe-lab4-forward-final-20261106-s3-1 Up 2 minutes (healthy)
hlpipe-lab4-forward-final-20261106-valkey-1 Up 3 minutes (healthy)
hlpipe-lab4-forward-final-20261106-api-1 12.78% 258.1MiB / 512MiB
hlpipe-lab4-forward-final-20261106-api-2 0.83% 298.8MiB / 512MiB
hlpipe-lab4-forward-final-20261106-postgres-1 0.13% 40.44MiB / 1GiB
hlpipe-lab4-forward-final-20261106-lb-1 0.14% 24.3MiB / 128MiB
hlpipe-lab4-forward-final-20261106-s3-1 0.04% 69.52MiB / 512MiB
hlpipe-lab4-forward-final-20261106-valkey-1 1.25% 13.12MiB / 128MiB
exit_code: 0 elapsed_seconds: 2.724
@@ -0,0 +1,17 @@
date: 2026-11-06T09:09:23Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ sh scripts/persistence-evidence.sh
date: 2026-11-06T09:09:23Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
== before: service hostname StartedAt status
api d4c8d53d7433 2026-11-06T09:09:18.754909134Z running
api da922ab2ea09 2026-11-06T09:09:18.824598676Z running
lb ea6930f64089 2026-11-06T09:09:12.580488131Z running
migrate adc778a3d97c 2026-11-06T09:09:13.657768882Z exited
postgres 3f3a870d89c0 2026-11-06T09:09:12.588930798Z running
s3 5921e788f03d 2026-11-06T09:09:12.58822809Z running
s3-init c90ac1d6c503 2026-11-06T09:09:18.165289926Z exited
valkey 07ea16e2fcfe 2026-11-06T09:09:12.587649298Z running
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
FAIL: GET /health/live: connection/TLS failure (URLError)
make: *** [test-persistence] Error 1
exit_code: 2 elapsed_seconds: 0.381
@@ -1,103 +0,0 @@
date: 2026-11-06T19:34:42Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
$ docker events --since 2026-11-06T19:34:12Z --until 2026-11-06T19:34:25Z --filter label=com.docker.compose.project=mtusi2026lab5 --filter type=container --format '{{.Time}} {{.Action}} {{index .Actor.Attributes "com.docker.compose.service"}} {{.Actor.ID}}'
1793993656 start s3 81f5d92e8b6e8e44a6627f4a6e8f9852773d2855e16fc4333402859430356a7f
1793993656 restart s3 81f5d92e8b6e8e44a6627f4a6e8f9852773d2855e16fc4333402859430356a7f
1793993656 start postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993656 restart postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993656 start valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993656 restart valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993657 exec_create: pg_isready -h 127.0.0.1 -U messenger -d messenger postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993657 exec_start: pg_isready -h 127.0.0.1 -U messenger -d messenger postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993657 exec_die postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993657 health_status: healthy postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993657 stop broker 7502f5de6c6ab0db594e6219925ad7902cf8d7fe7497d27821b3be9dbf4c8367
1793993657 die broker 7502f5de6c6ab0db594e6219925ad7902cf8d7fe7497d27821b3be9dbf4c8367
1793993657 start broker 7502f5de6c6ab0db594e6219925ad7902cf8d7fe7497d27821b3be9dbf4c8367
1793993657 restart broker 7502f5de6c6ab0db594e6219925ad7902cf8d7fe7497d27821b3be9dbf4c8367
1793993658 start lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993658 start migrate 5d51411de45f8fbacb9fee4ec2371f2789e1a131bc1dfbca088f47f3c54f1d6d
1793993658 exec_create: /bin/sh -c REDISCLI_AUTH="$(sed -n 's/^requirepass //p' /run/secrets/valkey.conf)" valkey-cli ping | grep -q PONG valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993658 exec_start: /bin/sh -c REDISCLI_AUTH="$(sed -n 's/^requirepass //p' /run/secrets/valkey.conf)" valkey-cli ping | grep -q PONG valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993658 exec_die valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993658 health_status: healthy valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993659 exec_create: pg_isready -h 127.0.0.1 -U messenger -d messenger postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993659 exec_start: pg_isready -h 127.0.0.1 -U messenger -d messenger postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993659 exec_die postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993659 exec_create: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993659 exec_start: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993659 exec_die lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993659 die migrate 5d51411de45f8fbacb9fee4ec2371f2789e1a131bc1dfbca088f47f3c54f1d6d
1793993659 exec_create: rabbitmq-diagnostics -q check_port_connectivity broker 7502f5de6c6ab0db594e6219925ad7902cf8d7fe7497d27821b3be9dbf4c8367
1793993659 exec_start: rabbitmq-diagnostics -q check_port_connectivity broker 7502f5de6c6ab0db594e6219925ad7902cf8d7fe7497d27821b3be9dbf4c8367
1793993660 exec_create: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993660 exec_start: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993660 exec_die lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993660 exec_die broker 7502f5de6c6ab0db594e6219925ad7902cf8d7fe7497d27821b3be9dbf4c8367
1793993660 health_status: healthy broker 7502f5de6c6ab0db594e6219925ad7902cf8d7fe7497d27821b3be9dbf4c8367
1793993660 exec_create: /bin/sh -c REDISCLI_AUTH="$(sed -n 's/^requirepass //p' /run/secrets/valkey.conf)" valkey-cli ping | grep -q PONG valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993660 exec_start: /bin/sh -c REDISCLI_AUTH="$(sed -n 's/^requirepass //p' /run/secrets/valkey.conf)" valkey-cli ping | grep -q PONG valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993660 exec_die valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993661 exec_create: pg_isready -h 127.0.0.1 -U messenger -d messenger postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993661 exec_start: pg_isready -h 127.0.0.1 -U messenger -d messenger postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993661 exec_die postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993661 exec_create: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993661 exec_start: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993661 exec_die lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993661 exec_create: curl -fsS -o /dev/null http://127.0.0.1:9000/health/ready s3 81f5d92e8b6e8e44a6627f4a6e8f9852773d2855e16fc4333402859430356a7f
1793993661 exec_start: curl -fsS -o /dev/null http://127.0.0.1:9000/health/ready s3 81f5d92e8b6e8e44a6627f4a6e8f9852773d2855e16fc4333402859430356a7f
1793993661 exec_die s3 81f5d92e8b6e8e44a6627f4a6e8f9852773d2855e16fc4333402859430356a7f
1793993661 health_status: healthy s3 81f5d92e8b6e8e44a6627f4a6e8f9852773d2855e16fc4333402859430356a7f
1793993662 start s3-init 6f3b94b9aeef24b8921a45a5d6f53a1dbbb337301787fd474496d9a24da65ed9
1793993662 exec_create: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993662 exec_start: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993662 exec_die lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993662 die s3-init 6f3b94b9aeef24b8921a45a5d6f53a1dbbb337301787fd474496d9a24da65ed9
1793993662 start relay e889034026d64612636cdc5bb76a459d6120b8308f17235b891275b8ef7a9a71
1793993662 start api 05aaa8c023d0644da201a9ae5909b29fb55135c1b73efef6db502d4fa6c15a01
1793993662 start worker 74094f96bf2a59407c41992311f2b072eed37ca5e9dc49689009c2ebbbda1206
1793993662 start api 9aa2e31be8d1f979e8059b563bae7449b0b3000707aad8d3b2bdb8fa06d1e442
1793993662 exec_create: /bin/sh -c REDISCLI_AUTH="$(sed -n 's/^requirepass //p' /run/secrets/valkey.conf)" valkey-cli ping | grep -q PONG valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993662 exec_start: /bin/sh -c REDISCLI_AUTH="$(sed -n 's/^requirepass //p' /run/secrets/valkey.conf)" valkey-cli ping | grep -q PONG valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993663 exec_die valkey ded0278c8247d20dc80367cff60cadf32ff0f0ef1c307137df734d5919094a97
1793993663 exec_create: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 05aaa8c023d0644da201a9ae5909b29fb55135c1b73efef6db502d4fa6c15a01
1793993663 exec_start: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 05aaa8c023d0644da201a9ae5909b29fb55135c1b73efef6db502d4fa6c15a01
1793993663 exec_create: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 9aa2e31be8d1f979e8059b563bae7449b0b3000707aad8d3b2bdb8fa06d1e442
1793993663 exec_start: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 9aa2e31be8d1f979e8059b563bae7449b0b3000707aad8d3b2bdb8fa06d1e442
1793993663 exec_create: pg_isready -h 127.0.0.1 -U messenger -d messenger postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993663 exec_start: pg_isready -h 127.0.0.1 -U messenger -d messenger postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993663 exec_die postgres 96be64dd1ce1d5df8def913cc66a94afa8f145acff473a60a2d774942a042ae2
1793993663 exec_create: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993663 exec_start: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993663 exec_die lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993663 exec_die api 05aaa8c023d0644da201a9ae5909b29fb55135c1b73efef6db502d4fa6c15a01
1793993663 exec_die api 9aa2e31be8d1f979e8059b563bae7449b0b3000707aad8d3b2bdb8fa06d1e442
1793993663 exec_create: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 05aaa8c023d0644da201a9ae5909b29fb55135c1b73efef6db502d4fa6c15a01
1793993663 exec_start: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 05aaa8c023d0644da201a9ae5909b29fb55135c1b73efef6db502d4fa6c15a01
1793993663 exec_create: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 9aa2e31be8d1f979e8059b563bae7449b0b3000707aad8d3b2bdb8fa06d1e442
1793993663 exec_start: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 9aa2e31be8d1f979e8059b563bae7449b0b3000707aad8d3b2bdb8fa06d1e442
1793993663 exec_create: curl -fsS -o /dev/null http://127.0.0.1:9000/health/ready s3 81f5d92e8b6e8e44a6627f4a6e8f9852773d2855e16fc4333402859430356a7f
1793993663 exec_start: curl -fsS -o /dev/null http://127.0.0.1:9000/health/ready s3 81f5d92e8b6e8e44a6627f4a6e8f9852773d2855e16fc4333402859430356a7f
1793993663 exec_die api 05aaa8c023d0644da201a9ae5909b29fb55135c1b73efef6db502d4fa6c15a01
1793993663 exec_die s3 81f5d92e8b6e8e44a6627f4a6e8f9852773d2855e16fc4333402859430356a7f
1793993664 exec_die api 9aa2e31be8d1f979e8059b563bae7449b0b3000707aad8d3b2bdb8fa06d1e442
1793993664 exec_create: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 05aaa8c023d0644da201a9ae5909b29fb55135c1b73efef6db502d4fa6c15a01
1793993664 exec_start: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 05aaa8c023d0644da201a9ae5909b29fb55135c1b73efef6db502d4fa6c15a01
1793993664 exec_create: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 9aa2e31be8d1f979e8059b563bae7449b0b3000707aad8d3b2bdb8fa06d1e442
1793993664 exec_start: python -c import sys,urllib.request;sys.exit(urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).status!=200) api 9aa2e31be8d1f979e8059b563bae7449b0b3000707aad8d3b2bdb8fa06d1e442
1793993664 exec_die api 05aaa8c023d0644da201a9ae5909b29fb55135c1b73efef6db502d4fa6c15a01
1793993664 health_status: healthy api 05aaa8c023d0644da201a9ae5909b29fb55135c1b73efef6db502d4fa6c15a01
1793993664 exec_create: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993664 exec_start: wget -q -O /dev/null http://127.0.0.1:8404/healthz lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993664 exec_die api 9aa2e31be8d1f979e8059b563bae7449b0b3000707aad8d3b2bdb8fa06d1e442
1793993664 health_status: healthy api 9aa2e31be8d1f979e8059b563bae7449b0b3000707aad8d3b2bdb8fa06d1e442
1793993664 exec_die lb 20bab8f9174fdb8c5b27adef097b805bef60d288609fae162bc2dffcadbbe40c
1793993664 exec_create: python -c import os,sys,time;sys.exit(time.time()-os.stat('/tmp/heartbeat').st_mtime>30) relay e889034026d64612636cdc5bb76a459d6120b8308f17235b891275b8ef7a9a71
1793993664 exec_start: python -c import os,sys,time;sys.exit(time.time()-os.stat('/tmp/heartbeat').st_mtime>30) relay e889034026d64612636cdc5bb76a459d6120b8308f17235b891275b8ef7a9a71
1793993664 exec_create: python -c import os,sys,time;sys.exit(time.time()-os.stat('/tmp/heartbeat').st_mtime>30) worker 74094f96bf2a59407c41992311f2b072eed37ca5e9dc49689009c2ebbbda1206
1793993664 exec_start: python -c import os,sys,time;sys.exit(time.time()-os.stat('/tmp/heartbeat').st_mtime>30) worker 74094f96bf2a59407c41992311f2b072eed37ca5e9dc49689009c2ebbbda1206
1793993664 exec_die relay e889034026d64612636cdc5bb76a459d6120b8308f17235b891275b8ef7a9a71
1793993664 health_status: healthy relay e889034026d64612636cdc5bb76a459d6120b8308f17235b891275b8ef7a9a71
1793993664 exec_die worker 74094f96bf2a59407c41992311f2b072eed37ca5e9dc49689009c2ebbbda1206
1793993664 health_status: healthy worker 74094f96bf2a59407c41992311f2b072eed37ca5e9dc49689009c2ebbbda1206
exit_code: 0 elapsed_seconds: 0.017
@@ -0,0 +1,26 @@
date: 2026-11-06T09:10:08Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-final-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1"}
$ sh scripts/persistence-evidence.sh http://127.0.0.1:18084
date: 2026-11-06T09:10:08Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
== before: service hostname StartedAt status
api d4c8d53d7433 2026-11-06T09:09:18.754909134Z running
api da922ab2ea09 2026-11-06T09:09:18.824598676Z running
lb ea6930f64089 2026-11-06T09:09:12.580488131Z running
migrate adc778a3d97c 2026-11-06T09:09:13.657768882Z exited
postgres 3f3a870d89c0 2026-11-06T09:09:12.588930798Z running
s3 5921e788f03d 2026-11-06T09:09:12.58822809Z running
s3-init c90ac1d6c503 2026-11-06T09:09:18.165289926Z exited
valkey 07ea16e2fcfe 2026-11-06T09:09:12.587649298Z running
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:18084"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
== after: service hostname StartedAt status
api d4c8d53d7433 2026-11-06T09:10:18.309662551Z running
api da922ab2ea09 2026-11-06T09:10:18.377623592Z running
lb ea6930f64089 2026-11-06T09:10:12.683407215Z running
migrate adc778a3d97c 2026-11-06T09:10:13.202156257Z exited
postgres 3f3a870d89c0 2026-11-06T09:10:12.374370839Z running
s3 5921e788f03d 2026-11-06T09:10:12.339453423Z running
s3-init c90ac1d6c503 2026-11-06T09:10:17.710432217Z exited
valkey 07ea16e2fcfe 2026-11-06T09:10:12.392600006Z running
exit_code: 0 elapsed_seconds: 13.179
@@ -1,7 +0,0 @@
date: 2026-11-06T19:34:12Z commit: 0e921116610d289716af0a40ec823376eb8bbcbc
environment: {"COMPOSE_PROJECT_NAME": "mtusi2026lab5", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18085", "LB_STATS_PORT": "25085", "BASE_URL": "http://127.0.0.1:18085", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:lab5-forward"}
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:18085"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
exit_code: 0 elapsed_seconds: 12.835
@@ -0,0 +1,37 @@
date: 2026-11-06T09:33:10Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {}
$ sh -c 'make lint && openspec validate --all --strict && openspec list --json && git diff --check && git diff --exit-code d7478726a85791c21e065d58f610735a9e687433 -- contracts tests README.md COURSE.md'
.venv/bin/ruff check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
All checks passed!
.venv/bin/ruff format --check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
163 files already formatted
.venv/bin/ty check src student-tests alembic
All checks passed!
- Validating...
✓ spec/lab1-event-publication
✓ spec/lab1-messenger-chats
✓ spec/lab1-messenger-history
✓ spec/lab1-messenger-identity
✓ spec/lab1-service-operability
✓ spec/lab2-auth-sessions
✓ spec/lab2-dependency-failures
✓ spec/lab2-history-index
✓ spec/lab2-persistent-storage
✓ spec/lab2-session-cache
✓ spec/lab3-failover-operations
✓ spec/lab3-idempotent-messages
✓ spec/lab3-load-balancing
✓ spec/lab4-attachments
✓ spec/lab4-evidence-runs
✓ spec/lab4-object-storage
✓ spec/lab4-storage-reconciler
✓ spec/lab4-upload-resilience
Totals: 18 passed, 0 failed (18 items)
{
"changes": [],
"root": {
"path": "<repo>",
"source": "nearest"
}
}
exit_code: 0 elapsed_seconds: 1.921
@@ -0,0 +1,19 @@
date: 2026-11-06T09:19:41Z commit: 75b93bbba5f29575d3fca1d013cc7e0770d88082
environment: {"COMPOSE_PROJECT_NAME": "hlpipe-lab4-forward-reconcile-20261106", "COMPOSE_FILE": "compose.yaml", "LB_HTTP_PORT": "18084", "LB_STATS_PORT": "24844", "BASE_URL": "http://127.0.0.1:18084", "EVIDENCE_DIR": "evidence/forward-final-2026-11-06", "NO_PROXY": "localhost,127.0.0.1,::1", "API_IMAGE": "mtusi-messenger:hlpipe-lab4-forward-final-20261106"}
$ make reconcile-demo 'ARGS=--out evidence/forward-final-2026-11-06/reconcile-demo'
python3 scripts/reconcile_track.py demo --base-url "http://127.0.0.1:18084" --out evidence/forward-final-2026-11-06/reconcile-demo
PASS dry-run находит каждый внедрённый класс, и найдено ровно внедрённое
PASS dry-run ничего не меняет
PASS apply исправляет ровно найденное dry-run, удаление намерений — в журнале аудита
PASS повторный apply — 0 действий
PASS независимая проверка после apply: нарушений нет, готовые не потеряны
PASS строки с расхождениями и ссылки сообщений сохранены
PASS карантин: метаданные 200, /content 404; нетронутое скачивается
PASS вернули те же байты — карантин снят; другие байты той же длины — остался
PASS второй одновременный проход пропущен
PASS SIGTERM: идущий проход останавливается за секунды, блокировка освобождена
PASS S3 остановлен: код 1 за ограниченное время, состояние не изменилось
PASS под нагрузкой: исправлены только внедрённые, ошибок нет
PASS под нагрузкой: все 201 готовы и совпадают по SHA-256, потерь 0
{"ok": true, "checks": 13}
exit_code: 0 elapsed_seconds: 257.493
@@ -0,0 +1,142 @@
{
"date": "2026-11-06T09:20:54Z",
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"mode": "apply",
"skipped": false,
"grace_seconds": 60,
"skew_seconds": 0,
"deep": true,
"page_size": 1000,
"scanned": {
"objects": 24,
"rows": 27
},
"found": {
"orphan_stale": 3,
"orphan_fresh": 2,
"missing": 3,
"size_mismatch": 3,
"sha_mismatch": 3,
"pending_stale": 6,
"pending_fresh": 2,
"quarantined": 0,
"healed": 0
},
"fixed": {
"orphan_stale": 3,
"missing": 3,
"size_mismatch": 3,
"sha_mismatch": 3,
"pending_stale": 6,
"healed": 0
},
"rechecked": {},
"errors": 0,
"samples": {
"missing": [
"01a1b028-2293-743d-a00c-f7fec1a50808",
"01a1b028-22ad-77fa-9b2e-d01e032a2c10",
"01a1b028-2306-74ed-9bff-7c2894a33621"
],
"size_mismatch": [
"01a1b028-22ba-778b-99d5-eef1d99349f1",
"01a1b028-2316-7510-b41e-754b39583de9",
"01a1b028-231e-70ba-8a9e-1de6d00c2e0d"
],
"sha_mismatch": [
"01a1b028-22c2-7713-adf4-93a25c06e07e",
"01a1b028-2327-7105-838f-3f0df5b10dc2",
"01a1b028-2330-7662-8f98-6b45a5c165a2"
],
"pending_stale": [
"2cc53ddd-063f-4edc-ae55-98f201965b7f",
"73fc548a-79a1-4396-a848-2e598eba75a1",
"848bed6c-437a-4169-8cca-940c1987055b",
"99d824a9-d16d-481e-9804-e209f2fa410b",
"a0a3b632-5fe3-447e-a93b-bbdce77c4fb1",
"d86c4cba-2836-4150-bf0e-d32e1ec442ec"
],
"orphan_stale": [
"attachments/35df74ac-5753-48e0-b106-d596db2ca8e6",
"attachments/8ba5a522-a4b8-40a8-b1f3-274401976db6",
"attachments/de3cc053-2a20-44ad-b223-e06818b039e7"
],
"orphan_fresh": [
"attachments/7b96d477-2dc4-4a8c-8703-e6176a7e46a6",
"attachments/d69d9843-ceab-4101-a278-7e5974071ac6"
],
"pending_fresh": [
"dfb03912-2304-4280-bfb7-7a7b9cb28597",
"f1cf4216-9e57-4217-866a-440aac9435f3"
]
},
"cost": {
"seconds": 0.119,
"requests": {
"s3_list": 1,
"s3_head": 6,
"s3_get": 13,
"s3_delete": 9,
"sql": 19
},
"waited_seconds": {
"s3_list": 0.018,
"sql": 0.006
},
"hashed_bytes": 1453621,
"cpu_seconds": 0.621,
"max_rss_mib": 107.6
},
"exit_code": 0,
"wall_seconds": 1.106,
"audit": [
{
"attachment_id": "2cc53ddd-063f-4edc-ae55-98f201965b7f",
"chat_id": "01a1b028-1d47-75b7-a3d7-f9dda0509d40",
"reason": "reconcile",
"event": "audit.attachment_discarded",
"level": "info",
"ts": "2026-11-06T09:20:54.712257Z"
},
{
"attachment_id": "73fc548a-79a1-4396-a848-2e598eba75a1",
"chat_id": "01a1b028-1d47-75b7-a3d7-f9dda0509d40",
"reason": "reconcile",
"event": "audit.attachment_discarded",
"level": "info",
"ts": "2026-11-06T09:20:54.724316Z"
},
{
"attachment_id": "848bed6c-437a-4169-8cca-940c1987055b",
"chat_id": "01a1b028-1d47-75b7-a3d7-f9dda0509d40",
"reason": "reconcile",
"event": "audit.attachment_discarded",
"level": "info",
"ts": "2026-11-06T09:20:54.732394Z"
},
{
"attachment_id": "99d824a9-d16d-481e-9804-e209f2fa410b",
"chat_id": "01a1b028-1d47-75b7-a3d7-f9dda0509d40",
"reason": "reconcile",
"event": "audit.attachment_discarded",
"level": "info",
"ts": "2026-11-06T09:20:54.741795Z"
},
{
"attachment_id": "a0a3b632-5fe3-447e-a93b-bbdce77c4fb1",
"chat_id": "01a1b028-1d47-75b7-a3d7-f9dda0509d40",
"reason": "reconcile",
"event": "audit.attachment_discarded",
"level": "info",
"ts": "2026-11-06T09:20:54.749494Z"
},
{
"attachment_id": "d86c4cba-2836-4150-bf0e-d32e1ec442ec",
"chat_id": "01a1b028-1d47-75b7-a3d7-f9dda0509d40",
"reason": "reconcile",
"event": "audit.attachment_discarded",
"level": "info",
"ts": "2026-11-06T09:20:54.757598Z"
}
]
}
@@ -0,0 +1,76 @@
{
"date": "2026-11-06T09:20:55Z",
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"mode": "apply",
"skipped": false,
"grace_seconds": 60,
"skew_seconds": 0,
"deep": true,
"page_size": 1000,
"scanned": {
"objects": 18,
"rows": 21
},
"found": {
"orphan_stale": 0,
"orphan_fresh": 2,
"missing": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale": 0,
"pending_fresh": 2,
"quarantined": 9,
"healed": 0
},
"fixed": {
"orphan_stale": 0,
"missing": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale": 0,
"healed": 0
},
"rechecked": {},
"errors": 0,
"samples": {
"quarantined": [
"01a1b028-2293-743d-a00c-f7fec1a50808",
"01a1b028-22ad-77fa-9b2e-d01e032a2c10",
"01a1b028-22ba-778b-99d5-eef1d99349f1",
"01a1b028-2306-74ed-9bff-7c2894a33621",
"01a1b028-2316-7510-b41e-754b39583de9",
"01a1b028-231e-70ba-8a9e-1de6d00c2e0d",
"01a1b028-22c2-7713-adf4-93a25c06e07e",
"01a1b028-2327-7105-838f-3f0df5b10dc2",
"01a1b028-2330-7662-8f98-6b45a5c165a2"
],
"orphan_fresh": [
"attachments/7b96d477-2dc4-4a8c-8703-e6176a7e46a6",
"attachments/d69d9843-ceab-4101-a278-7e5974071ac6"
],
"pending_fresh": [
"dfb03912-2304-4280-bfb7-7a7b9cb28597",
"f1cf4216-9e57-4217-866a-440aac9435f3"
]
},
"cost": {
"seconds": 0.043,
"requests": {
"s3_list": 1,
"s3_head": 0,
"s3_get": 13,
"s3_delete": 0,
"sql": 1
},
"waited_seconds": {
"s3_list": 0.017,
"sql": 0.006
},
"hashed_bytes": 1453621,
"cpu_seconds": 0.595,
"max_rss_mib": 107.4
},
"exit_code": 0,
"wall_seconds": 1.021,
"audit": []
}
@@ -0,0 +1,53 @@
{
"checked_at": "2026-11-06T09:20:57Z",
"grace_seconds": 60,
"deep": true,
"objects": 18,
"rows": 21,
"ready_healthy": 10,
"counts": {
"orphan_stale": 0,
"orphan_fresh": 2,
"missing_referenced": 0,
"missing_unreferenced": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale_with_object": 0,
"pending_stale_without_object": 0,
"pending_fresh": 2,
"quarantined": 9,
"incomplete_stale": 0,
"incomplete_fresh": 0,
"lost_ready": 0
},
"samples": {
"orphan_fresh": [
"attachments/7b96d477-2dc4-4a8c-8703-e6176a7e46a6",
"attachments/d69d9843-ceab-4101-a278-7e5974071ac6"
],
"pending_fresh": [
"dfb03912-2304-4280-bfb7-7a7b9cb28597",
"f1cf4216-9e57-4217-866a-440aac9435f3"
],
"quarantined": [
"01a1b028-2293-743d-a00c-f7fec1a50808",
"01a1b028-22ad-77fa-9b2e-d01e032a2c10",
"01a1b028-22ba-778b-99d5-eef1d99349f1",
"01a1b028-22c2-7713-adf4-93a25c06e07e",
"01a1b028-2306-74ed-9bff-7c2894a33621",
"01a1b028-2316-7510-b41e-754b39583de9",
"01a1b028-231e-70ba-8a9e-1de6d00c2e0d",
"01a1b028-2327-7105-838f-3f0df5b10dc2",
"01a1b028-2330-7662-8f98-6b45a5c165a2"
]
},
"seconds": {
"s3_list": 0.3,
"s3_incomplete": 0.325,
"pg_query": 0.128,
"deep_hash": 0.593,
"total": 1.348
},
"violations": [],
"ok": true
}
@@ -0,0 +1,82 @@
{
"checked_at": "2026-11-06T09:20:51Z",
"grace_seconds": 60,
"deep": true,
"objects": 24,
"rows": 27,
"ready_healthy": 10,
"counts": {
"orphan_stale": 3,
"orphan_fresh": 2,
"missing_referenced": 2,
"missing_unreferenced": 1,
"size_mismatch": 3,
"sha_mismatch": 3,
"pending_stale_with_object": 3,
"pending_stale_without_object": 3,
"pending_fresh": 2,
"quarantined": 0,
"incomplete_stale": 0,
"incomplete_fresh": 0,
"lost_ready": 0
},
"samples": {
"orphan_stale": [
"attachments/35df74ac-5753-48e0-b106-d596db2ca8e6",
"attachments/8ba5a522-a4b8-40a8-b1f3-274401976db6",
"attachments/de3cc053-2a20-44ad-b223-e06818b039e7"
],
"orphan_fresh": [
"attachments/7b96d477-2dc4-4a8c-8703-e6176a7e46a6",
"attachments/d69d9843-ceab-4101-a278-7e5974071ac6"
],
"missing_referenced": [
"01a1b028-2293-743d-a00c-f7fec1a50808",
"01a1b028-22ad-77fa-9b2e-d01e032a2c10"
],
"missing_unreferenced": [
"01a1b028-2306-74ed-9bff-7c2894a33621"
],
"size_mismatch": [
"01a1b028-22ba-778b-99d5-eef1d99349f1",
"01a1b028-2316-7510-b41e-754b39583de9",
"01a1b028-231e-70ba-8a9e-1de6d00c2e0d"
],
"sha_mismatch": [
"01a1b028-22c2-7713-adf4-93a25c06e07e",
"01a1b028-2327-7105-838f-3f0df5b10dc2",
"01a1b028-2330-7662-8f98-6b45a5c165a2"
],
"pending_stale_with_object": [
"848bed6c-437a-4169-8cca-940c1987055b",
"a0a3b632-5fe3-447e-a93b-bbdce77c4fb1",
"d86c4cba-2836-4150-bf0e-d32e1ec442ec"
],
"pending_stale_without_object": [
"2cc53ddd-063f-4edc-ae55-98f201965b7f",
"73fc548a-79a1-4396-a848-2e598eba75a1",
"99d824a9-d16d-481e-9804-e209f2fa410b"
],
"pending_fresh": [
"dfb03912-2304-4280-bfb7-7a7b9cb28597",
"f1cf4216-9e57-4217-866a-440aac9435f3"
]
},
"seconds": {
"s3_list": 0.304,
"s3_incomplete": 0.347,
"pg_query": 0.112,
"deep_hash": 0.556,
"total": 1.319
},
"violations": [
"orphan_stale",
"missing_referenced",
"missing_unreferenced",
"size_mismatch",
"sha_mismatch",
"pending_stale_with_object",
"pending_stale_without_object"
],
"ok": false
}
@@ -0,0 +1,44 @@
{
"checked_at": "2026-11-06T09:23:59Z",
"grace_seconds": 60,
"deep": true,
"objects": 3382,
"rows": 3383,
"ready_healthy": 3375,
"counts": {
"orphan_stale": 0,
"orphan_fresh": 0,
"missing_referenced": 0,
"missing_unreferenced": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale_with_object": 0,
"pending_stale_without_object": 0,
"pending_fresh": 0,
"quarantined": 8,
"incomplete_stale": 0,
"incomplete_fresh": 0,
"lost_ready": 0
},
"samples": {
"quarantined": [
"01a1b028-22ad-77fa-9b2e-d01e032a2c10",
"01a1b028-22ba-778b-99d5-eef1d99349f1",
"01a1b028-22c2-7713-adf4-93a25c06e07e",
"01a1b028-2306-74ed-9bff-7c2894a33621",
"01a1b028-2316-7510-b41e-754b39583de9",
"01a1b028-231e-70ba-8a9e-1de6d00c2e0d",
"01a1b028-2327-7105-838f-3f0df5b10dc2",
"01a1b028-2330-7662-8f98-6b45a5c165a2"
]
},
"seconds": {
"s3_list": 0.677,
"s3_incomplete": 0.367,
"pg_query": 0.149,
"deep_hash": 67.224,
"total": 68.428
},
"violations": [],
"ok": true
}
@@ -0,0 +1,245 @@
{
"date": "2026-11-06T09:23:59Z",
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"started_at": "2026-11-06T09:19:42Z",
"faults": {
"injected": {
"orphan_stale": [
"35df74ac-5753-48e0-b106-d596db2ca8e6",
"de3cc053-2a20-44ad-b223-e06818b039e7",
"8ba5a522-a4b8-40a8-b1f3-274401976db6"
],
"missing": [
"01a1b028-2306-74ed-9bff-7c2894a33621",
"01a1b028-22ad-77fa-9b2e-d01e032a2c10",
"01a1b028-2293-743d-a00c-f7fec1a50808"
],
"size_mismatch": [
"01a1b028-231e-70ba-8a9e-1de6d00c2e0d",
"01a1b028-22ba-778b-99d5-eef1d99349f1",
"01a1b028-2316-7510-b41e-754b39583de9"
],
"sha_mismatch": [
"01a1b028-2330-7662-8f98-6b45a5c165a2",
"01a1b028-2327-7105-838f-3f0df5b10dc2",
"01a1b028-22c2-7713-adf4-93a25c06e07e"
],
"pending_stale": [
"2cc53ddd-063f-4edc-ae55-98f201965b7f",
"99d824a9-d16d-481e-9804-e209f2fa410b",
"73fc548a-79a1-4396-a848-2e598eba75a1",
"a0a3b632-5fe3-447e-a93b-bbdce77c4fb1",
"848bed6c-437a-4169-8cca-940c1987055b",
"d86c4cba-2836-4150-bf0e-d32e1ec442ec"
],
"orphan_fresh": [
"d69d9843-ceab-4101-a278-7e5974071ac6",
"7b96d477-2dc4-4a8c-8703-e6176a7e46a6"
],
"pending_fresh": [
"f1cf4216-9e57-4217-866a-440aac9435f3",
"dfb03912-2304-4280-bfb7-7a7b9cb28597"
]
},
"targets": {
"missing": [
"01a1b028-2293-743d-a00c-f7fec1a50808",
"01a1b028-22ad-77fa-9b2e-d01e032a2c10",
"01a1b028-2306-74ed-9bff-7c2894a33621"
],
"corrupt": [
"01a1b028-22ba-778b-99d5-eef1d99349f1",
"01a1b028-2316-7510-b41e-754b39583de9",
"01a1b028-231e-70ba-8a9e-1de6d00c2e0d"
],
"bitflip": [
"01a1b028-22c2-7713-adf4-93a25c06e07e",
"01a1b028-2327-7105-838f-3f0df5b10dc2",
"01a1b028-2330-7662-8f98-6b45a5c165a2"
]
},
"linked": [
"01a1b028-2293-743d-a00c-f7fec1a50808",
"01a1b028-22ad-77fa-9b2e-d01e032a2c10",
"01a1b028-22ba-778b-99d5-eef1d99349f1",
"01a1b028-22c2-7713-adf4-93a25c06e07e",
"01a1b028-22cb-73b4-92c8-0db140de50a1",
"01a1b028-22d2-7761-8bdd-8b9987dcd70f"
]
},
"seconds": 256.6,
"checks": [
{
"name": "dry-run находит каждый внедрённый класс, и найдено ровно внедрённое",
"ok": true,
"expected": {
"orphan_stale": 3,
"missing": 3,
"size_mismatch": 3,
"sha_mismatch": 3,
"pending_stale": 6,
"orphan_fresh": 2,
"pending_fresh": 2,
"quarantined": 0
},
"found": {
"orphan_stale": 3,
"orphan_fresh": 2,
"missing": 3,
"size_mismatch": 3,
"sha_mismatch": 3,
"pending_stale": 6,
"pending_fresh": 2,
"quarantined": 0,
"healed": 0
}
},
{
"name": "dry-run ничего не меняет",
"ok": true,
"objects": [
24,
24
],
"rows": [
27,
27
]
},
{
"name": "apply исправляет ровно найденное dry-run, удаление намерений — в журнале аудита",
"ok": true,
"dry_run": {
"orphan_stale": 3,
"missing": 3,
"size_mismatch": 3,
"sha_mismatch": 3,
"pending_stale": 6
},
"fixed": {
"orphan_stale": 3,
"missing": 3,
"size_mismatch": 3,
"sha_mismatch": 3,
"pending_stale": 6
},
"audit_discarded": 6
},
{
"name": "повторный apply — 0 действий",
"ok": true,
"fixed": {
"orphan_stale": 0,
"missing": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale": 0,
"healed": 0
},
"found": {
"orphan_stale": 0,
"orphan_fresh": 2,
"missing": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale": 0,
"pending_fresh": 2,
"quarantined": 9,
"healed": 0
}
},
{
"name": "независимая проверка после apply: нарушений нет, готовые не потеряны",
"ok": true,
"counts": {
"orphan_stale": 0,
"orphan_fresh": 2,
"missing_referenced": 0,
"missing_unreferenced": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale_with_object": 0,
"pending_stale_without_object": 0,
"pending_fresh": 2,
"quarantined": 9,
"incomplete_stale": 0,
"incomplete_fresh": 0,
"lost_ready": 0
}
},
{
"name": "строки с расхождениями и ссылки сообщений сохранены",
"ok": true,
"quarantine": {
"01a1b028-2293-743d-a00c-f7fec1a50808": "missing",
"01a1b028-22ad-77fa-9b2e-d01e032a2c10": "missing",
"01a1b028-22ba-778b-99d5-eef1d99349f1": "size_mismatch",
"01a1b028-22c2-7713-adf4-93a25c06e07e": "sha_mismatch",
"01a1b028-2306-74ed-9bff-7c2894a33621": "missing",
"01a1b028-2316-7510-b41e-754b39583de9": "size_mismatch",
"01a1b028-231e-70ba-8a9e-1de6d00c2e0d": "size_mismatch",
"01a1b028-2327-7105-838f-3f0df5b10dc2": "sha_mismatch",
"01a1b028-2330-7662-8f98-6b45a5c165a2": "sha_mismatch"
},
"message_links": 6
},
{
"name": "карантин: метаданные 200, /content 404; нетронутое скачивается",
"ok": true
},
{
"name": "вернули те же байты — карантин снят; другие байты той же длины — остался",
"ok": true,
"fixed": {
"orphan_stale": 0,
"missing": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale": 0,
"healed": 1
},
"s3_get": 5
},
{
"name": "второй одновременный проход пропущен",
"ok": true
},
{
"name": "SIGTERM: идущий проход останавливается за секунды, блокировка освобождена",
"ok": true,
"s3": "paused",
"state_before_stop": "running",
"init": "true",
"stop_seconds": 0.1,
"exit_code": 143,
"next_pass_skipped": false
},
{
"name": "S3 остановлен: код 1 за ограниченное время, состояние не изменилось",
"ok": true,
"exit_code": 1,
"wall_seconds": 2.32
},
{
"name": "под нагрузкой: исправлены только внедрённые, ошибок нет",
"ok": true,
"fixed": {
"orphan_stale": 5,
"missing": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale": 5
},
"runs": 59
},
{
"name": "под нагрузкой: все 201 готовы и совпадают по SHA-256, потерь 0",
"ok": true,
"uploads": {
"201": 3364
},
"lost_ready": 0
}
],
"ok": true
}
@@ -0,0 +1,93 @@
{
"date": "2026-11-06T09:20:52Z",
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"mode": "dry-run",
"skipped": false,
"grace_seconds": 60,
"skew_seconds": 0,
"deep": true,
"page_size": 1000,
"scanned": {
"objects": 24,
"rows": 27
},
"found": {
"orphan_stale": 3,
"orphan_fresh": 2,
"missing": 3,
"size_mismatch": 3,
"sha_mismatch": 3,
"pending_stale": 6,
"pending_fresh": 2,
"quarantined": 0,
"healed": 0
},
"fixed": {
"orphan_stale": 0,
"missing": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale": 0,
"healed": 0
},
"rechecked": {},
"errors": 0,
"samples": {
"missing": [
"01a1b028-2293-743d-a00c-f7fec1a50808",
"01a1b028-22ad-77fa-9b2e-d01e032a2c10",
"01a1b028-2306-74ed-9bff-7c2894a33621"
],
"size_mismatch": [
"01a1b028-22ba-778b-99d5-eef1d99349f1",
"01a1b028-2316-7510-b41e-754b39583de9",
"01a1b028-231e-70ba-8a9e-1de6d00c2e0d"
],
"sha_mismatch": [
"01a1b028-22c2-7713-adf4-93a25c06e07e",
"01a1b028-2327-7105-838f-3f0df5b10dc2",
"01a1b028-2330-7662-8f98-6b45a5c165a2"
],
"pending_stale": [
"2cc53ddd-063f-4edc-ae55-98f201965b7f",
"73fc548a-79a1-4396-a848-2e598eba75a1",
"848bed6c-437a-4169-8cca-940c1987055b",
"99d824a9-d16d-481e-9804-e209f2fa410b",
"a0a3b632-5fe3-447e-a93b-bbdce77c4fb1",
"d86c4cba-2836-4150-bf0e-d32e1ec442ec"
],
"orphan_stale": [
"attachments/35df74ac-5753-48e0-b106-d596db2ca8e6",
"attachments/8ba5a522-a4b8-40a8-b1f3-274401976db6",
"attachments/de3cc053-2a20-44ad-b223-e06818b039e7"
],
"orphan_fresh": [
"attachments/7b96d477-2dc4-4a8c-8703-e6176a7e46a6",
"attachments/d69d9843-ceab-4101-a278-7e5974071ac6"
],
"pending_fresh": [
"dfb03912-2304-4280-bfb7-7a7b9cb28597",
"f1cf4216-9e57-4217-866a-440aac9435f3"
]
},
"cost": {
"seconds": 0.04,
"requests": {
"s3_list": 1,
"s3_head": 0,
"s3_get": 13,
"s3_delete": 0,
"sql": 1
},
"waited_seconds": {
"s3_list": 0.016,
"sql": 0.006
},
"hashed_bytes": 1453621,
"cpu_seconds": 0.594,
"max_rss_mib": 107.4
},
"exit_code": 0,
"wall_seconds": 1.013,
"audit": []
}
@@ -0,0 +1,78 @@
{
"date": "2026-11-06T09:20:59Z",
"commit": "75b93bbba5f29575d3fca1d013cc7e0770d88082",
"mode": "apply",
"skipped": false,
"grace_seconds": 60,
"skew_seconds": 0,
"deep": false,
"page_size": 1000,
"scanned": {
"objects": 20,
"rows": 21
},
"found": {
"orphan_stale": 0,
"orphan_fresh": 2,
"missing": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale": 0,
"pending_fresh": 2,
"quarantined": 8,
"healed": 1
},
"fixed": {
"orphan_stale": 0,
"missing": 0,
"size_mismatch": 0,
"sha_mismatch": 0,
"pending_stale": 0,
"healed": 1
},
"rechecked": {},
"errors": 0,
"samples": {
"quarantined": [
"01a1b028-22ba-778b-99d5-eef1d99349f1",
"01a1b028-2306-74ed-9bff-7c2894a33621",
"01a1b028-2316-7510-b41e-754b39583de9",
"01a1b028-231e-70ba-8a9e-1de6d00c2e0d",
"01a1b028-22ad-77fa-9b2e-d01e032a2c10",
"01a1b028-2330-7662-8f98-6b45a5c165a2",
"01a1b028-22c2-7713-adf4-93a25c06e07e",
"01a1b028-2327-7105-838f-3f0df5b10dc2"
],
"orphan_fresh": [
"attachments/7b96d477-2dc4-4a8c-8703-e6176a7e46a6",
"attachments/d69d9843-ceab-4101-a278-7e5974071ac6"
],
"pending_fresh": [
"dfb03912-2304-4280-bfb7-7a7b9cb28597",
"f1cf4216-9e57-4217-866a-440aac9435f3"
],
"healed": [
"01a1b028-2293-743d-a00c-f7fec1a50808"
]
},
"cost": {
"seconds": 0.04,
"requests": {
"s3_list": 1,
"s3_head": 0,
"s3_get": 5,
"s3_delete": 0,
"sql": 2
},
"waited_seconds": {
"s3_list": 0.019,
"sql": 0.006
},
"hashed_bytes": 559085,
"cpu_seconds": 0.607,
"max_rss_mib": 107.5
},
"exit_code": 0,
"wall_seconds": 1.074,
"audit": []
}

Some files were not shown because too many files have changed in this diff Show More