Commit Graph
12 Commits
Author SHA1 Message Date
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
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 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 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 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 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 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 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 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 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