1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Add attachments (protocol 4), their edge-case tests, and handoff docs

- One optional attachment per message, any size up to the server's
  MaxAttachmentSize (default 1G), sent and stored in 1 MB parts, checked
  with its SHA-256. Uploaded before its message (UploadStart, UploadChunk),
  then attached by the PushMessage in the same transaction; uploads never
  pushed expire after UploadTimeout. Read back a part at a time
  (GetAttachment).
- Replicated separately, after the messages: the message carries the size
  and SHA-256, then each check-in lists what the peer is missing
  (MissingAttachments) and sends the parts from where it stopped. Over the
  receiver's limit, the attachment is marked not kept.
- Deleted with its message by the retention, parts cleaned up in the
  background. Schema v7 (attachments, blobs, blob_chunks), replacing the
  unused attachements table.
- DLL: PushMessageWithFile/WithData, SaveAttachment, LoadAttachment,
  GetMessageAttachmentSize, IsMessageAttachmentReady. Python: push(...,
  attachment=), get_attachment(), save_attachment(). Tools: PushMessage -a,
  GetAttachment. The release smoke test round-trips one.
- Tests/Attachments-Test.ps1 (39 checks) and Tests/AttachmentEdges-Test.ps1
  (51 checks, with a raw protocol client): wrong SHA-256, bad parts,
  others' uploads, expiry, replication resuming after a kill, a corrupted
  stored copy. Found: a corrupted copy is re-sent to peers forever, noted
  as open item 3 in Notes.md with a proposed fix.
- CLAUDE.md: how to build, test, the traps and working rules, for the next
  session. Notes.md and the Design docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVPXGLs3KK1MAQn3ouP
This commit is contained in:
2026-11-08 18:56:15 +01:00
parent 9caf816dca
commit df61ef9719
42 changed files with 4920 additions and 106 deletions
+162
View File
@@ -0,0 +1,162 @@
# Attachments
A message can have **one attachment**: any bytes (a file, a photo, a dump),
of any size up to the server's `MaxAttachmentSize` (default 1 GB, at most
1 TB). Most messages have none. The message's JSON can say what it is: the
attachment itself has no name or type, only its size and SHA-256.
Protocol version 4. Code: `Server/Storage/Attachments.pbi` (storage),
`Server/Networking/Networking.pbi` (requests), `Server/Networking/Peers.pbi`
(replication), `Client/BakaShrot_Client.pbi` (DLL).
## The rules
- **Sent and stored in parts** of 1 MB (`#BakaShrot_AttachmentChunkSize`, the
last one what's left), one request each: neither end ever holds a whole
attachment in memory (a 512 MB one: the server peaked at 15 MB).
- **Checked with its SHA-256**, given before the first part: the server
checks it once all parts are in (uploads and replicated ones alike), the
client when it reads one back.
- **A message is only stored once all of its attachment is.** The client
uploads it first, then pushes the message with the upload's id: readers
never see a message whose attachment is missing on the server it was
pushed to. Messages stay immutable.
- **Replicated after the messages**, separately: a peer gets the message
first (with the attachment's size and SHA-256), then its data once the
messages are caught up. So on the other servers, a message can be there
before its attachment: `AttachmentReady` tells.
- **Deleted with its message** (the retention): its parts go a few at a
time, in the background.
## Pushing one
```
C -> S UploadStart(topic, size, sha256) same permissions as pushing to that
topic, size <= MaxAttachmentSize
S -> C UploadStarted(upload id, 1 MB)
C -> S UploadChunk(upload id, 0, data) in order, each the right size
S -> C ChunkStored(received, complete 0)
...
C -> S UploadChunk(upload id, last, data)
server: reads all of it back, checks the SHA-256 (or drops it, refused)
S -> C ChunkStored(received = size, complete 1)
C -> S PushMessage(topic, json, upload id)
server: the upload must be this client's (its node), for that topic,
complete: the message and its attachment are stored together
S -> C MessagePushed(id)
```
- An upload belongs to the client's node and the topic it was started for.
- One not pushed within `UploadTimeout` seconds (default 3600) is deleted.
- A refused part doesn't drop the upload; a SHA-256 mismatch does.
- The DLL does all of it in `BakaShrot_PushMessageWithFile()` /
`_WithData()`; it reads a file twice (the SHA-256 first).
## Reading one
```
C -> S GetAttachment(topic, node, message id, part) same permissions as reading
S -> C AttachmentChunk(ids, message id, size, sha256, part, data)
```
Any part, in any order (the DLL reads them in order). Refused if the
message has none, or if it isn't all on this server yet (replicated after
its message), or isn't kept here (bigger than this server's
`MaxAttachmentSize`).
## Replicating
On its link to a peer, at every check-in, once the messages are sent
(`Design/Packets.md`, Replication):
```
P -> S MissingAttachmentsRequest
S -> P MissingAttachments([(topic, node, message id, next part)])
up to 256 attachments of messages S has,
from what it takes from P, not all here
P: for each one it has, all of it, and sends S (SendTopics/SendNodes):
P -> S ReplicateAttachmentChunk(topic, node, message id, part, data)
S -> P ChunkStored(received, complete)
... from the part S asked for: resumes after a dropped link
S: once all of it is in, checks the SHA-256 its message came with:
ready, or dropped and asked for again from the start
```
- A server relays what it has: an attachment that isn't on P either is
skipped, S asks again at the next check-in, maybe of another peer.
- An attachment bigger than S's `MaxAttachmentSize` is marked not kept
when its message arrives: S never asks for it.
- A message skipped on arrival (past S's max age) has no attachment row:
never asked for either.
## Storage (schema v7, `db_schema_v7.dbml`)
| Table | What |
|---|---|
| `attachments` | A message's: size, SHA-256, its blob once any of it is here, state: 0 missing, 1 receiving, 2 ready, 3 not kept. |
| `blobs` | The data of one attachment: whose (topic, node), size, SHA-256, bytes received, state: 0 receiving, 1 complete (an upload waiting for its message), 2 attached, 3 to delete. |
| `blob_chunks` | Its parts, 1 MB each, by (blob, index). |
- Triggers: deleting a message deletes its `attachments` row, which marks
its blob to delete. The retention thread (`Retention.pbi`) deletes those
parts 32 at a time, along with uploads past `UploadTimeout`, every
`RetentionInterval` seconds, retention rules or not.
- Parts are written through the writer (each one its own transaction), read
on each thread's own connection.
- SQLite reuses the freed pages; `vacuum` gives the space back to the disk.
## In the clients
| | DLL | Python | Tools |
|---|---|---|---|
| Push with one | `BakaShrot_PushMessageWithFile(Topic, Json, Path)`, `_WithData(Topic, Json, *Data, Size)` | `push(data, topic, attachment=bytes or path)` | `PushMessage -a <File>` |
| Does a message have one | `BakaShrot_GetMessageAttachmentSize()`, `BakaShrot_IsMessageAttachmentReady()` | `Message.attachment_size`, `.attachment_ready` | `GetLatestMessage` prints it |
| Read one | `BakaShrot_SaveAttachment(Topic, Node, Id, Path)`, `_LoadAttachment()` + `_GetAttachmentData()` | `save_attachment()`, `get_attachment()` | `GetAttachment <Topic> <Node> <Id> <OutFile>` |
## Speed
On one machine (i5-13500, localhost, PB 5.73): 5 MB up in ~80 ms and down
in ~65 ms through the tools; 512 MB up in 8.5 s (SHA-256 on both ends
included) and down in 3.9 s. One part per round trip: over a slow link,
latency adds up (1000 round trips per GB).
## Tested
- `Tests/Attachments-Test.ps1` (39 checks, two servers, ports 12410-12411):
one part, several, an exact multiple, one byte; none; replicated
identical; not kept past the other server's limit; too big to push;
deleted with its message, parts included.
- `Tests/AttachmentEdges-Test.ps1` (51 checks, ports 12413-12414), with a
raw protocol client (`Tests/AttachmentEdgeClient.pb`) for what the DLL
never sends:
- a wrong SHA-256: refused at the last part, the upload dropped, pushing
with it refused;
- parts out of order, of the wrong size, repeated, past the end, from
another client: refused, the upload goes on;
- someone else's upload, the wrong topic, attached twice, an unknown id,
too big, a topic the client may not push to or read: refused, the
connection stays up;
- uploads left behind (half sent, complete but never pushed): kept within
`UploadTimeout`, deleted past it (10.7 s for 10), then refused;
- replication resuming: the receiver killed at ~45 MB of 400 MB,
restarted: what it had committed is still there, the sender goes on
from that part, the result is identical;
- a byte flipped in the sender's database: the client refuses it
(SHA-256), the peer drops it, serves nothing, and asks again.
- `check_bakashrot.py` (Python): bytes and files, round trips, refusals.
## Not done
- **Resuming an upload** after a dropped connection: the parts are kept
until `UploadTimeout`, but the DLL starts over. (Replication resumes.)
- **Several parts in flight**, for links with high latency.
- **A corrupted copy is sent again and again.** If a server's own stored
copy is damaged (disk, a bug), its peers drop it at every check-in and
ask again: the whole attachment is re-sent every `PeerSyncInterval`
(6 times in 6 s in the test). The server itself never notices, it serves
the damaged parts to clients too (they refuse them, by their SHA-256).
Fix: when a peer answers "doesn't match", the sender checks its own copy
(`HashStorageBlob()`); if it's damaged, it marks it missing, so it gets a
good one back from another peer, and stops sending it. Details, and how
the test should change: `Notes.md`, open item 3.
- **No deduplication**: the same file attached twice is stored twice.
+31 -9
View File
@@ -20,13 +20,17 @@ Reference for working on BakaShrot's networking. Related docs:
| Sealed Hello, key exchange; encrypting a buffer | `Commons/Cryptography/Session.pbi`, `Commons/Cryptography/Cipher.pbi` |
| Client side of the handshake, on any connection | `Commons/Networking/Outbound.pbi` |
| Server: listener, one thread per client, request handlers | `Server/Networking/Networking.pbi` |
| Server: links to peers, check-ins, sending missing messages | `Server/Networking/Peers.pbi` |
| Server: links to peers, check-ins, sending missing messages and attachments | `Server/Networking/Peers.pbi` |
| Server: storing messages (the writer), attachments, deleting old ones | `Server/Storage/Writer.pbi`, `Attachments.pbi`, `Retention.pbi` |
| Server: its config, and the example one | `Server/Config/Config.pbi`, `Server/Config/schema.ini` |
| Server: the root thread, which stops and starts every worker (restart, vacuum) | `Server/Root.pbi` |
| Client DLL (one connection) | `Client/BakaShrot_Client.pbi`, used through `BakaShrot_Client_Prototypes.pbi` |
| Python client, over the DLL | `Interactors/Python/bakashrot.py` |
| Tests of the packets alone, without sockets | `Tests/HandshakeTest.pb` |
| Tests of the cipher and the session crypto, without sockets | `Tests/CipherTest.pb` |
| What goes over the wire (a recording proxy) | `Tests/wire_check.py`, run by `Tests/Python-Test.ps1` |
| A raw protocol client, for what the DLL never sends | `Tests/AttachmentEdgeClient.pb`, run by `Tests/AttachmentEdges-Test.ps1` |
| Every end-to-end suite | `Tests/*.ps1`, listed in `CLAUDE.md` |
## Transport and framing
@@ -70,10 +74,10 @@ Reference for working on BakaShrot's networking. Related docs:
array, read in order with PB-MessagePack:
1. `Magic` (integer), always `#BakaShrot_ProtocolMagic` (`0x42534854`,
"BSHT").
2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (3: the
Hello sealed, a key per connection, everything after the
ChallengeRequest encrypted; 2 had topics and nodes by name, in plain
text; 1 had ids only).
2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (4:
attachments; 3: the Hello sealed, a key per connection, everything
after the ChallengeRequest encrypted, times; 2 had topics and nodes by
name, in plain text; 1 had ids only).
3. `PacketType` (integer), one of the ids below.
4. The packet's own fields, in the order listed.
- **Encodings:** strings are UTF-8 MessagePack strings, the nonce a
@@ -119,14 +123,14 @@ over its own link to another server.
| 5 | ChallengeRequest | S→C | `ChallengeB64` str (32 bytes), `Nonce` bin (32 bytes), `ServerSessionKey` bin (32 bytes), `ServerSignature` bin (64 bytes, of the transcript). The last packet in plain text | ChallengeResponse |
| 6 | ChallengeResponse | C→S | `ChallengeResponseB64` str (64-byte signature of the transcript), `Nonce` bin (32 bytes) | AuthAccepted |
| 7 | AuthAccepted | S→C | None. | |
| 8 | PushMessage | C→S | `Topic` str (ref, "" for the client's own), `JsonData` str | MessagePushed / RequestRefused |
| 8 | PushMessage | C→S | `Topic` str (ref, "" for the client's own), `JsonData` str, `UploadId` int (its attachment, 0 for none) | MessagePushed / RequestRefused |
| 9 | MessagePushed | S→C | `MessageId` int ≥ 1 | |
| 10 | GetLatestMessage | C→S | `Topic` str (ref), `Node` str (ref) | LatestMessage / RequestRefused |
| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str | |
| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str, `AttachmentSize` int (0 for none), `AttachmentReady` int 0/1 | |
| 12 | RequestRefused | S→C | `Reason` str, for logs and humans | |
| 13 | SyncStateRequest | P→S | None. | SyncState / RequestRefused |
| 14 | SyncState | S→P | `TopicCount` int, then each topic's `Id` int and `Name` str (the named topics S takes from P); `NodeCount` int, then each node's `Id` and `Name` (the named nodes S takes from P); `TopicPatternCount` int, then each pattern str; `NodePatternCount` int, then each pattern str (S's wildcards for P, `*` included); `PairCount` int, then each pair's `TopicId`, `NodeId`, `MessageId`. Ids are S's own, names are never digits | |
| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin) and `JsonData` str | MessagePushed (last id) / RequestRefused |
| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin), `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentSha256` bin (32 bytes, empty for none) | MessagePushed (last id) / RequestRefused |
| 16 | QueryRequest | C→S | `Sql` str | QueryResult / RequestRefused |
| 17 | QueryResult | S→C | `JsonResult` str: `{"columns":[...],"rows":[[...],...]}`, every value a string or null | |
| 18 | ResolveName | C→S | `Kind` int (1 topic, 2 node), `Ref` str | NameResolved / RequestRefused |
@@ -134,7 +138,20 @@ over its own link to another server.
| 20 | ListNames | C→S | `Kind` int (1 topics, 2 nodes) | NamesList |
| 21 | NamesList | S→C | `Kind` int, `Truncated` int 0/1, `Count` int, then each entry's `Id` int, `Name` str ("" if unnamed), `Origin` str ("config", "id") | |
| 22 | GetMessages | C→S | `Topic` str (ref), `Node` str (ref), `AfterMessageId` int ≥ 0, `Limit` int 1-10000 | Messages / RequestRefused |
| 23 | Messages | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `More` int 0/1, `Count` int 0-10000, then each message's `MessageId` int (≥ 1, strictly increasing, above `AfterMessageId`), `PushedAt` int and `JsonData` str | |
| 23 | Messages | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `More` int 0/1, `Count` int 0-10000, then each message's `MessageId` int (≥ 1, strictly increasing, above `AfterMessageId`), `PushedAt` int, `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentReady` int 0/1 | |
| 24 | UploadStart | C→S | `Topic` str (ref, "" for the client's own), `Size` int 1-MaxAttachmentSize, `Sha256` bin (32 bytes) | UploadStarted / RequestRefused |
| 25 | UploadStarted | S→C | `UploadId` int ≥ 1, `ChunkSize` int (1 MB) | |
| 26 | UploadChunk | C→S | `UploadId` int, `ChunkIndex` int ≥ 0 (the next one), `Data` bin (1 MB, the last one what's left) | ChunkStored / RequestRefused |
| 27 | ChunkStored | S→C, S→P | `Received` int (bytes so far), `Complete` int 0/1 (all of it, SHA-256 checked) | |
| 28 | GetAttachment | C→S | `Topic`, `Node` str (refs), `MessageId` int ≥ 1, `ChunkIndex` int ≥ 0 | AttachmentChunk / RequestRefused |
| 29 | AttachmentChunk | S→C | `TopicId`, `NodeId` int (the server's), `MessageId` int, `Size` int, `Sha256` bin (32 bytes), `ChunkIndex` int, `Data` bin | |
| 30 | MissingAttachmentsRequest | P→S | None. | MissingAttachments / RequestRefused |
| 31 | MissingAttachments | S→P | `Count` int 0-256, then each one's `Topic`, `Node` str (names), `MessageId` int, `NextChunk` int | |
| 32 | ReplicateAttachmentChunk | P→S | `Topic`, `Node` str (names), `MessageId` int, `ChunkIndex` int (the next one), `Data` bin | ChunkStored / RequestRefused |
**Attachments** (24-32, and the attachment fields): see
`Design/Attachments.md`. At most one per message, in parts of 1 MB, checked
with their SHA-256, replicated after their message.
**Times** (`PushedAt`): milliseconds since 1970-01-01 00:00:00 UTC, 1 to
`#BakaShrot_MaxTimestamp` (9999-12-31), anything else aborts. A message is
@@ -267,6 +284,11 @@ P -> S ReplicateMessages the topic and node names, the next missing messages
S -> P MessagePushed(id) the batch stored in one transaction with
INSERT OR IGNORE, the last id echoed
... until caught up, or the first refusal for that pair
then the attachments of the messages S now has:
P -> S MissingAttachmentsRequest
S -> P MissingAttachments what S lacks, among what it takes from P
P -> S ReplicateAttachmentChunk ... -> S -> P ChunkStored, per part
(Design/Attachments.md)
```
- **Batch size:** `PeerBatchSize` is set on the sending side, in
+7 -4
View File
@@ -24,11 +24,14 @@ database:
view with `is_json = 1`;
- if `python` is on the PATH, reads them and pushes one with
`python\bakashrot.py`;
- pushes a 3 MB attachment with `PushMessage.exe -a` and reads it back
identical with `GetAttachment.exe`;
- then force-kills the server and deletes everything.
The end-to-end tests in `Tests/` cover much more (names, replication, big
messages, GetMessages, the Python client), but against `Build\` (PB 5.73)
and `BenchServer.exe`, not the release.
messages, GetMessages, the Python client, retention, attachments and their
edge cases), but against `Build\` (PB 5.73) and `BenchServer.exe`, not the
release. The list is in `CLAUDE.md`.
## Fixed: the release needed the Visual C++ runtime
@@ -110,7 +113,7 @@ in `Tests/` already, to be pointed at the release instead.
10. **Version hygiene**:
- `-Version 1.0.0` refuses a dirty tree instead of appending `-dirty`;
- the release commit is tagged (`v1.0.0`), the version comes from it;
- `VERSION.txt` gives the protocol version (3) and the runtime needed;
- `VERSION.txt` gives the protocol version (4) and the runtime needed;
- the Python client is checked on the oldest version it claims (3.8),
not only on the latest (3.14 here).
@@ -210,7 +213,7 @@ Notes for when the builds move to a pipeline.
- `Build.ps1` ends by running the server, which waits on its console:
needs a `-NoRun` switch. It also writes private keys into `Build\`,
which must never be published as an artifact.
- The tests use fixed ports (12399 for the release, 12401-12409 for
- The tests use fixed ports (12399 for the release, 12401-12414 for
`Tests/`): parallel jobs on one runner collide, make them parameters
or pick free ones.
- One entry point that runs every test (`Tests/*.ps1`, the handshake