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

Moved the PureBasic version to OldSource/, Started the Rust rewrite in Source/

The rewrite's plan and decisions are in revamp.md. Steps 0 to 10 are done:
the workspace and checks, bakashrot-proto, bakashrot-pki and
bakashrot-cert, bakashrot-config, bakashrot-storage (schema v9), the
server and the client library (every request but replication's,
attachments and retention included), the C DLL with its C, PureBasic and
Python bindings, and the bakashrot tool. Step 11 (replication) is next.

OldSource/ is the old implementation, kept building and passing as the
reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
2026-11-14 12:47:40 +01:00
parent d0048b17c8
commit e044fcf359
225 changed files with 21849 additions and 123 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.
+154
View File
@@ -0,0 +1,154 @@
# Certificates - X.509 with Ed25519
Status (2026-11-13): an include in `Commons/Cryptography/`, tested on its
own and against OpenSSL, **not used by anything yet**. Next: a tool that
generates certificates, then the server and the client loading and
checking them (see the end).
## Why it's written here
- **libsodium has no X.509 or ASN.1**, so the DER and the certificate
structure are PureBasic (`Der.pbi`, `X509.pbi`). Every bit of
cryptography is still libsodium's: Ed25519 signatures, SHA-256 (key ids,
fingerprints), random serials, Base64 (PEM) and hex, seeds to key pairs
(PKCS#8).
- **Not the OS's APIs:** Windows' CryptoAPI can't check Ed25519
certificates, and the identity keys are Ed25519 already. Not OpenSSL
either: another library to ship and load on both OSes, for what's a few
hundred lines of DER. One code for Windows and Linux.
- **Standard certificates all the same:** OpenSSL reads them, verifies
chains of them, reads the private keys, and they read and check OpenSSL's
(`Tests/X509-Test.ps1`).
## Files
| File | What |
|---|---|
| `Commons/Cryptography/Der.pbi` | ASN.1 DER: a reader (strict) and a writer, integers, OIDs (any arc size), times, strings, bit strings. |
| `Commons/Cryptography/X509.pbi` | Certificates: reading, issuing, checking, PEM, PKCS#8 private keys. Includes `Der.pbi` and `Libsodium.pbi`. |
| `Tests/X509Test.pb` | 131 checks on its own, 145 with OpenSSL's certificates. |
| `Tests/X509-Test.ps1` | Runs it, makes OpenSSL's certificates for it, checks its own with OpenSSL. |
## Reading
- `BakaShrot_X509_Parse(*Der, Size)`, `_ParsePem(Text)`, `_Load(Path)`
(PEM or DER, by its first byte) give a `BakaShrot_X509Certificate`, freed
with `BakaShrot_X509_Free()`. Failures give 0 and a code.
- **Any certificate is read** (RSA, ECDSA...): version, serial, names,
validity, algorithms, every extension. Only Ed25519 ones have their key
and signature (`HasEd25519Key`, `HasEd25519Signature`), and only they can
be checked or issue others (`Unsupported` otherwise).
- **Strict DER:** shortest lengths and integers, no indefinite lengths, real
dates, no NUL in strings, the inner and outer signature algorithms the same
bytes, an extension once at most, v1 never written as such, nothing after
the certificate. A reader never reads past its buffer. Every truncation of
a certificate is refused, and of its 503 one-bit flips, the 335 that still
parse all fail the checks.
- **Known extensions** fill fields: BasicConstraints (`IsCa`,
`PathLength`), KeyUsage (`KeyUsage`, `#BakaShrot_X509_KeyUsage_*` flags),
the key ids (`SubjectKeyId`, `AuthorityKeyId`, hex). The others stay as
they are (`Extensions()`: OID, critical, DER value).
- Names keep their attributes in order (`Subject\Attributes()`): OID, text,
string type, RDN index. `BakaShrot_X509_NameGet(@\Subject, "CN")`,
`_NameToString()` ("CN=kitchen, OU=clients").
## Issuing
`BakaShrot_X509_Issue(*Template, *Issuer, *IssuerPrivateKey, *OutSize)`,
the issuer 0 for a self-signed one. The template: subject, validity, the
subject's public key, CA or not and its path length, key usage, the custom
extensions. It writes:
- v3, a random positive 16-byte serial (or the template's), Ed25519.
- The issuer's subject as the issuer certificate encodes it (so names match
byte for byte).
- Names one attribute per RDN: `C` as a PrintableString (2 letters),
`emailAddress` and `DC` as IA5String, the rest UTF8String.
- UTCTime from 1950 to 2049, GeneralizedTime otherwise (RFC 5280).
- BasicConstraints (critical, always), KeyUsage (critical, if any), the
subject's key id (the first 20 bytes of the key's SHA-256, RFC 7093) and
the issuer's, then the template's extensions in order.
It refuses: a private key that isn't the issuer's (or the subject's when
self-signed), an issuer that isn't a CA or lacks keyCertSign, a path length
on a leaf, NotAfter before NotBefore, a name it can't write.
## Checking
Each returns `#BakaShrot_X509_Ok` (0) or what's wrong
(`BakaShrot_X509_ErrorName()`): BadSignature, NotYetValid, Expired,
IssuerMismatch, NotCa, PathTooLong, UnknownCritical, Unsupported...
- `BakaShrot_X509_CheckIssuedBy(*Cert, *Issuer, Now, Handled)`: one link.
The issuer names match (as encoded), the key ids too when both have one,
the issuer may issue, the signature is its key's, `*Cert` is valid at
`Now` (both ends included), no critical extension is left unhandled.
- `BakaShrot_X509_VerifyChain(Chain(), *Root, Now, Handled)`: the leaf
first, then each issuer up to the one the trusted `*Root` issued. Every
link as above, the root valid and a CA, the path lengths kept.
- `_CheckSignature()`, `_CheckValidity()`, `_CanIssue()`,
`_CheckCriticalExtensions()` on their own.
- `Now` is seconds since 1970 UTC: `BakaShrot_X509_Now()`.
- `Handled` lists the critical extensions the caller understands
(`"oid;oid"`). RFC 5280: a critical extension a reader doesn't know makes
the certificate unusable.
## Custom extensions
- **BakaShrot's OID arc:** `#BakaShrot_Oid_Arc`,
`2.25.232025699926348910519219903487382490981`, a UUID OID (ITU-T X.667),
which needs no registration (made from a random UUID, 2026-11-13). It
could be swapped for a registered enterprise number (`1.3.6.1.4.1.<PEN>`)
as long as no certificate was issued for real with it.
- **Extensions:** `#BakaShrot_Oid_Extensions` (the arc + `.1`) + `.<n>`,
numbered as they're defined, a number never reused. None is defined yet;
the tests use 9000 and up.
- **Writing:** `BakaShrot_X509_AddTextExtension(@Template, Oid, Text)`
(UTF8String), `_AddIntegerExtension()`, `_AddExtension()` (any one DER
element, a `BakaShrot_DerWriter` makes them), critical or not.
- **Reading:** `BakaShrot_X509_GetExtensionText()`,
`_GetExtensionInteger()`, or `_FindExtension()` and the raw value.
- **Critical or not:** critical means "refuse me if you don't know me". For
fields only BakaShrot reads, non-critical is the usual choice; critical
if a reader that ignores it would grant too much (then pass it in
`Handled`).
- OpenSSL writes them too (`<oid> = ASN1:UTF8String:...` in an extensions
file, as the test does), and shows them by OID.
## Private keys and PEM
- `BakaShrot_X509_PrivateKeyToPem()` / `_PrivateKeyFromPem()`: PKCS#8
(RFC 8410), what `openssl genpkey -algorithm ed25519` writes, not
encrypted. Reading takes v1 and v2 (with the public key, which must
match). The seed and the DER are wiped after use.
- `BakaShrot_Pem_Encode()` / `_Decode()` for any label, LF line endings;
CRLF, spaces and text around the block are fine on reading.
## Threads
No globals. A parsed certificate is only read once made, and its names and
extensions are arrays, not lists (`ForEach` moves a list's current element,
see `CLAUDE.md`): any number of threads may check against the same CA.
## Not done
- **Using it:** a tool generating a CA, server and client certificates and
keys; the server and client loading them, checking the other end's. How
they'd fit the handshake (what replaces or joins the `PublicKeys` lists,
the ClientHello carrying a certificate, the 4 KB handshake frame limit) is
to decide with the client auth rework: a protocol change either way.
- **Revocation:** no CRL or OCSP. Short validities, or a list of revoked
serials or fingerprints in the configs, if it's ever needed.
- **Not interpreted:** SubjectAltName, ExtendedKeyUsage, NameConstraints,
policies. They're read as raw extensions; marked critical (NameConstraints
usually is), they make a certificate refused unless in `Handled`.
- **Names are matched as encoded**, byte for byte, not with RFC 5280's
case-insensitive comparison. Fine for certificates issued here, which
copy the issuer's encoding; another CA's could differ in string types.
- Multi-valued RDNs are read, not written (one attribute per RDN).
Encrypted PKCS#8, certificate requests (CSR): not done.
- `BakaShrot_X509_Now()` repeats `BakaShrot_NowUtcMs()`
(`Server/Storage/Storage.pbi`) in seconds, so `Commons/` doesn't depend on
the server: one could move to `Commons/` for both.
- Tested on Windows (5.73, 6.40 C) only so far; the Linux side
(`gettimeofday`, `-lsodium`) is the same code as elsewhere but unrun.
+231
View File
@@ -0,0 +1,231 @@
# Cryptography - what's done, what isn't
Status (protocol 3, 2026-11-08): every connection is encrypted and
authenticated, and both ends prove who they are.
- The client seals its Hello for the server's public key: only that server
can read it, and nobody watching learns who connects.
- Both ends make a key pair for this connection, sign the exchange with
their identity keys, and get the connection's keys from it.
- Everything after the ChallengeRequest is encrypted, both ways.
Still not done: messages aren't signed by the node that wrote them, and
keys sit in plain-text ini files (see the end).
## Library
- **libsodium 1.0.22**, the official MSVC release's dynamic build.
- `Build.ps1` extracts it from `Libs/libsodium-1.0.22-msvc.zip` to
`Libs/libsodium/{x64,x86}/`, and copies `libsodium.dll` next to the
programs.
- Linux would link `-lsodium` instead (untested).
- It needs the Visual C++ runtime (`vcruntime140.dll`), packaged with the
release from `Libs/redist/` (`Libs/redist/README.md`).
- **Wrappers:** `Commons/Cryptography/Libsodium.pbi` is the only file that
imports it. On top of it, nothing else calls libsodium:
- `Cipher.pbi`: encrypting and decrypting buffers with a connection's keys.
- `Session.pbi`: the handshake's part, the sealed Hello and the key
exchange.
- The handshake itself, what's signed and in which order, is in
`Commons/Networking/Connections.pbi`.
- **Imported functions:**
| libsodium | Wrapper | Notes |
|---|---|---|
| `sodium_init` | `InitCryptography()` | Called before any use; repeated calls are fine. |
| `crypto_sign_keypair` | `GenerateKeyPair()` | Used by `Tools/BakaShrotGenerateKeyPairs`. |
| `crypto_sign_detached` | `EncodeData()`, `BakaShrot_SignHandshake()` | **Signs**, the name `EncodeData` is wrong. |
| `crypto_sign_verify_detached` | `DecodeData()`, `BakaShrot_VerifyHandshake()` | **Verifies**, the name `DecodeData` is wrong. |
| `crypto_sign_ed25519_sk_to_pk` | `GetPublicKeyFromPrivateKey()` | Lets a server only keep its private key in its config. |
| `crypto_sign_ed25519_pk_to_curve25519` / `_sk_to_curve25519` | `BakaShrot_Session_SealHello()` / `_LoadHelloKeys()` | The X25519 key of an Ed25519 identity, for the sealed Hello. |
| `crypto_box_seal` / `_seal_open` | `BakaShrot_Session_SealHello()` / `_OpenHello()` | The Hello, sealed for the server. |
| `crypto_kx_keypair` | `BakaShrot_Session_NewKeyPair()` | One per connection and end. |
| `crypto_kx_client_session_keys` / `_server_session_keys` | `BakaShrot_Session_StartClient()` / `_StartServer()` | A key per direction, into the cipher. |
| `crypto_aead_xchacha20poly1305_ietf_encrypt` / `_decrypt` | `BakaShrot_Cipher_Encrypt()`, `_EncryptTo()` / `_Decrypt()` | Every packet after the ChallengeRequest. |
| `crypto_aead_xchacha20poly1305_ietf_keygen` | `BakaShrot_Cipher_GenerateKey()` | Tests only, real keys come from the handshake. |
| `sodium_memzero` | `BakaShrot_Cipher_Clear()`, the `_Clear*()` of `Session.pbi` | Wipes keys. |
| `crypto_hash_sha256` | `BakaShrot_X509_KeyId()`, `_Fingerprint()` | Certificates' key ids and fingerprints (`Design/Certificates.md`). |
| `randombytes_buf` | `BakaShrot_X509_Issue()` | Random serial numbers. |
| `crypto_sign_seed_keypair` / `crypto_sign_ed25519_sk_to_seed` | `BakaShrot_X509_PrivateKeyFromPem()` / `_PrivateKeyToPem()` | PKCS#8 files hold the 32-byte seed. |
| `sodium_bin2base64` / `_base642bin` / `_base64_encoded_len` | `BakaShrot_Pem_Encode()` / `_Decode()` | PEM; line breaks skipped. |
| `sodium_bin2hex` / `_hex2bin` | `BakaShrot_X509_Hex()` / `_FromHex()` | Serials, key ids. |
- **Base64 helpers**, in `Libsodium.pbi`:
- `EncodeKeyToString()` encodes a key or signature.
- `DecodeKeyFromString()` refuses anything that doesn't decode to exactly
the expected size.
## Keys
- **Identity keys: Ed25519.** A private key is 64 bytes (libsodium's
format: the seed followed by the public key), a public key 32, a
signature 64. One key both signs and receives the sealed Hello (its X25519
form, libsodium's conversion).
- **Stored as Base64 in ini files, in plain text:**
- A server's own key: `[BakaShrot] PrivateKey`. The server logs its
public key when it starts.
- Who it trusts: `[BakaShrot.Client.<name>] PublicKeys` and
`[BakaShrot.Peer.<name>] PublicKey`. The peer's is also the server it
expects at the other end of its link, so it's required.
- A client's: whatever the app passes to `BakaShrot_SetPrivateKey()`,
`BakaShrot_SetPublicKey()` and `BakaShrot_SetServerPublicKey()` (the
server's). The tools and `bakashrot.py` read them from `client.ini`:
`PrivateKey`, `PublicKey`, `ServerPublicKey`.
- **Connection keys: X25519**, made for each connection by both ends, the
secrets wiped once the cipher has its keys. So a recorded connection
can't be decrypted later, even with both identity keys (forward secrecy).
- **Generated** by `Tools/BakaShrotGenerateKeyPairs`, which `Build.ps1` runs
on every build.
- **Wiping:**
- Wiped from memory after use: BakaShrotGenerateKeyPairs; a server's key when it stops, and
its peer links'; every connection's keys when it ends.
- Not wiped: the client DLL's global copy of its private key, and the
config structures holding the Base64 text.
- **No rotation or revocation**, other than editing the configs and
restarting.
## Randomness
The challenge (32 bytes) and the nonce (32 bytes) come from PureBasic's
`OpenCryptRandom()` / `CryptRandomData()`, which use the OS's secure
generator. The connection key pairs and the sealed Hello's throwaway key
come from libsodium's.
## The handshake
See `Design/Packets.md` for the packets, `Connections.pbi` for the code.
The client knows the server's public key beforehand.
1. **Hello, sealed** (`crypto_box_seal` for the server's key): the client's
node (the one it writes as), its Base64 public key, and the public half
of a key pair it made for this connection.
2. The server opens it (another server can't: abort), decodes the key and
checks that a `[BakaShrot.Client.<name>]` has this `Node` and lists this
key.
3. **ChallengeRequest, in plain text:** a fresh random challenge and nonce,
the public half of the server's own pair for this connection, and the
server's signature of the transcript.
4. The client checks the signature with the server's public key: it's the
right server, and nobody swapped a half on the way. Both ends get the
connection's keys from both pairs (`crypto_kx`), every packet from here
on is encrypted (the cipher, below).
5. **ChallengeResponse:** the client signs the transcript, and echoes the
nonce.
6. The server checks the nonce is the one it issued for this connection,
and the signature against the key from the Hello. **AuthAccepted.**
**The transcript** (`BakaShrot_HandshakeTranscript`, 208 bytes) is what
both sign: a label (`"BakaShrot3 srv"` or `"BakaShrot3 cli"`, padded to 16
bytes, so one end's signature can't pass as the other's), the client's and
the server's identity keys, both halves, the challenge and the nonce. So
each signature only holds for this connection, between these two.
What that gets, and why:
- **Only the right server gets anywhere.** The Hello is sealed for it, and
the client won't send anything else until the server signed this
connection's halves with the key the client expects.
- **Only the registered client authenticates.** Same as before: it signs
the challenge, now along with the halves.
- **Nobody in the middle.** Swapping a half breaks a signature; relaying
untouched gets the relay nothing, it doesn't have the secrets.
- **Replays fail.** A replayed Hello gets a fresh challenge and server half,
which the replayer can't answer: the client's half is the client's. A
replayed packet later fails the cipher's sequence check.
- **Hijacking an authenticated connection fails:** an injected packet
doesn't decrypt, the connection is aborted.
- **Hidden from someone watching:** who connects (sealed Hello) and
everything after the ChallengeRequest. Not hidden: that it's BakaShrot,
the server's half and signature, packet sizes and timing.
The nonce is redundant with the challenge (both are fresh, random, and
signed), but it's harmless and kept as designed.
## The cipher (`Commons/Cryptography/Cipher.pbi`)
The crypto of the data itself, so no packet handler or framing code has to
do any: a `BakaShrot_Cipher` per connection holds the keys, then takes
buffers. `BakaShrot_ConnectionMetadata\Cipher`, set up by the handshake.
- **`BakaShrot_Cipher_InitWithKeys(*Cipher, *SendKey, *ReceiveKey)`**: a key
per direction, as the handshake gives them (refuses the same key twice).
Or **`_Init(*Cipher, *Key, Role)`**, one key shared by both ends, `Role`
`#BakaShrot_Cipher_Client` or `#BakaShrot_Cipher_Server`.
- **`BakaShrot_Cipher_Encrypt(*Cipher, *Data, Size, *OutSize)`** returns a new
buffer: `[sequence number, 8 bytes][encrypted data][16-byte tag]`, 24 bytes
more than the data (`#BakaShrot_Cipher_Overhead`). `_EncryptTo()` writes it
into a given buffer (the frame, in `BakaShrot_SendPacket()`).
- **`BakaShrot_Cipher_Decrypt(*Cipher, *Sealed, Size, *OutSize)`** returns the
data in a new buffer, or 0: then abort the connection.
- **`BakaShrot_Cipher_Clear(*Cipher)`** wipes the keys once done.
What it guarantees: nobody without the key reads, changes, forges or
truncates a buffer (XChaCha20-Poly1305, libsodium's AEAD), and nobody
replays, reorders, drops or reflects one: each carries its sequence number,
the receiver only takes the next one, and each direction has its own key
(or its own nonces with one key). Nonces never repeat within a key: a key is
only ever used for one connection.
Why XChaCha20-Poly1305 with sequence numbers rather than
`crypto_secretstream_*`: same primitives, but the buffers stay independent
(no stream state beyond the counter), the format is simple to describe in
`Design/Packets.md`, and replay/reorder protection comes from the sequence
check, which TCP's ordering makes strict.
**Where it's used:** in the framing, so the packets don't know about it.
`BakaShrot_SendPacket()` encrypts when given the connection's cipher (0 only
for the Hello and the ChallengeRequest), `BakaShrot_OpenFrame()` decrypts a
frame once the cipher is set up. On the server, the client's own thread
decrypts, outside the server's mutex; the listener only gathers bytes.
Frames are up to `#BakaShrot_MaxPacketSize + #BakaShrot_Cipher_Overhead`
once authenticated.
## Tests
- `Tests/CipherTest.pb` (56 checks, PB 5.73 and 6.40's C backend), without
sockets:
- The cipher: both directions, a bit flipped at every byte refused, cut
short, replayed, reordered, reflected to its sender or to another client
with the same key, another key, empty data, 16 MB (~33 ms both ways),
two keys, clearing, `_EncryptTo()`.
- The session: a sealed Hello only its server opens, without the identity
showing, tampered or cut short refused, an invalid server key refused;
the key exchange agrees both ways, a key per direction, the pairs wiped,
a swapped half or another connection's keys don't decrypt, an all-zero
half refused.
- `Tests/wire_check.py`, run by `Tests/Python-Test.ps1`: a proxy between
the client and the server records every byte. The pushed message, the
client's topic, node and public key never show up in it; a byte flipped
after the handshake drops the connection ("doesn't decrypt" in the
server's log); another server's public key can't connect ("isn't sealed
for this server").
- `Tests/HandshakeTest.pb`: the handshake packets' fields, without crypto.
- Every end-to-end test (`Tests/*.ps1`, the release's smoke test) runs over
encrypted connections, peer links included.
## What's NOT done (in rough order of importance)
1. **Messages aren't signed by the node that first wrote them,** so
replicated data can't be verified: a peer is trusted with what it sends
(`Design/ReplicationIssues.md`, issue 3).
2. **Private keys sit in plain-text ini files.**
3. **No key rotation or revocation**, and no way to pin more than one key
for a server (to change it without a flag day).
4. **One identity key signs and opens sealed boxes** (its X25519 form).
libsodium supports it and it's a common pattern, but a separate key for
each would be cleaner.
5. **Anyone can make the server work a little:** each new connection costs
it opening a sealed box, a key pair and a signature before the client
proved anything (before: one signature check). Only the 4 KB handshake
limit and the timeout bound it, no rate limit.
6. **The client DLL doesn't wipe its private key**, nor the configs their
Base64 text.
## Ideas for when it gets abstracted
- **A small interface**, so libsodium can be swapped or wrapped without
touching the networking: `Sign`, `Verify`, `GenerateKeyPair`,
`PublicKeyFromPrivateKey`, `Random`, plus `Session.pbi` and `Cipher.pbi`
as they are. Rename `EncodeData`/`DecodeData` to `Sign`/`Verify` while at
it.
- **Per-message signatures** by the origin node, stored with the message and
checked on replication, for item 1.
+362
View File
@@ -0,0 +1,362 @@
# Protocol - packets, flows and conventions
Reference for working on BakaShrot's networking. Related docs:
- `Design/Cryptography.md`: how the handshake proves both ends and sets up
the encryption, and what's still left.
- `Design/ReplicationIssues.md`: known replication problems, with a benchmark.
- `Design/StorageConcurrency.md`: the database threading problem and its
planned fix.
## Where things live
| What | Where |
|---|---|
| Packet base, type ids, limits | `Commons/Networking/Packets.pbi` |
| What a topic or node "ref" is: a name or an id | `Commons/Networking/Names.pbi` |
| Server: which name every id has, translating names to ids | `Server/Storage/Names.pbi` |
| One file per packet, with its `_Encode` and `_Decode` | `Commons/Networking/Packets/*.pbi` |
| Framing (and its encryption), connection metadata, the signed handshake transcript, `BakaShrot_GetPacketType` | `Commons/Networking/Connections.pbi` |
| 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 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` |
| Ready-to-run setups (configs, start scripts, a README each) | `Examples/`, listed in `Examples/README.md` |
| Tools: connecting through the DLL from an ini; ending (waits for Enter when started from Explorer) | `Tools/Common/ToolClient.pbi`, `Tools/Common/ToolConsole.pbi` |
| 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
- **TCP, IPv4.** A server listens on `[BakaShrot.Server] Host:Port`.
- **Frames:** every packet is sent as one frame: its size as a **4-byte
little-endian** unsigned integer, followed by the packet itself.
- `BakaShrot_SendPacket()` sends a frame and loops until all of it is
sent.
- **Encryption:** the frame's content, not its size:
- Frame 1, the Hello: sealed for the server's public key
(`crypto_box_seal`, 48 bytes more).
- Frame 2, the ChallengeRequest: plain text, signed by the server.
- Every frame after it, both ways: encrypted with the connection's keys
(`Cipher.pbi`): `[sequence number, 8 bytes LE][encrypted packet][16-byte
tag]`, 24 bytes more. A frame that doesn't decrypt, or out of sequence,
aborts the connection. `BakaShrot_SendPacket()` encrypts when given
the cipher, `BakaShrot_OpenFrame()` decrypts once it's set up.
- `BakaShrot_Inbox_*` gathers received bytes and takes complete frames out
of them.
- **Limits:**
- A packet is 1 to `#BakaShrot_MaxHandshakePacketSize` (4 KB) bytes until
the other end is authenticated, then 1 to `#BakaShrot_MaxPacketSize`
(16 MB, plus the 24 bytes of encryption). A frame announcing anything
else is invalid, as soon as its
4-byte size arrived. The server lifts it (`BakaShrot_Inbox_Lift()`)
before sending AuthAccepted, the client once it got it. So anyone can
connect, but only those with a key can make the other end hold big
frames.
- At most 2 frames' worth of data may wait, unread, in an inbox
(`BakaShrot_Inbox_MaxSize()`: ~8 KB, then ~32 MB).
- Breaking either limit aborts the connection.
- A pushed message is at most `#BakaShrot_MaxMessageSize` (16 MB - 4 KB)
of UTF-8, refused above (by the client DLL already), so a stored
message fits in every packet that carries one later: LatestMessage, a
ReplicateMessages batch of one, without the fields around it going over.
- **Encrypted and authenticated:** see `Design/Cryptography.md`.
## Packet layout
- **A packet is a plain sequence of MessagePack values**, not a map or an
array, read in order with PB-MessagePack:
1. `Magic` (integer), always `#BakaShrot_ProtocolMagic` (`0x42534854`,
"BSHT").
2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (6:
refusals carry a code; 5: the Hello carries the node only, the default
topic is the server's; 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
MessagePack binary.
- **Decoding:** `BakaShrot_ReadPacketBase()` checks the magic, the version
and that the type is positive. Each `_Decode` then checks it's **its own**
type, and checks every field's MessagePack type, read error and range.
Anything wrong means the whole packet is rejected.
- **Not checked:** trailing data after the last field is ignored.
### Topics and nodes: names and ids
- **Each server has its own ids** (0-65535) for topics and nodes, and
gives them to the names: the config lists the topics
(`[BakaShrot.Topics]`), the nodes come from the sections that define
them (its own, its peers', its clients') and optionally
`[BakaShrot.Nodes]`; a name keeps the id the database has for it, a new
one gets the lowest free one (`Server/Storage/Names.pbi`). The **name is
what's shared**: "logs" can be 1 on one server and 200 on another.
- **A ref** is how a packet gives a topic or node: a name (1-64 of
`A-Z a-z 0-9 _ . -`, not only digits, any case), or an id in digits,
which always means that id on the receiving server. An unnamed topic or
node goes by its id in digits.
- **Clients** give refs in their requests, the server resolves them in its
own names. **Servers** send names to each other, never rely on ids
matching: the sync state maps the sender's ids to names, and the batches
carry names.
- **Only what's named on both servers replicates.** Unnamed topics and
nodes, and names the other server doesn't have, are dropped, unless the
receiver's `AcceptTopics` / `AcceptNodes` for that peer has a wildcard
(`*`, `sensors.*`; `AcceptNodes` is `*` by default) matching it: it's then added there with an id of its
own. The sync state lists every name the receiver takes, and its
wildcards, so the sender only sends those and nothing gets refused at
every check-in.
### Packet types
Direction: **C** client, **S** server, **P** peer, a server acting as a client
over its own link to another server.
| Id | Packet | Dir | Fields, in order | Answered by |
|---|---|---|---|---|
| 0 | None | | Never valid. | |
| 1-3 | | | Used by the removed `AuthenticationPacket.pbi`, don't reuse. | |
| 4 | ClientHello | C→S | `ClientNode` str (ref, the node it writes as), `ClientPubKeyB64` str, `ClientSessionKey` bin (32 bytes). Sent sealed for the server's key | ChallengeRequest |
| 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, `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, `AttachmentSize` int (0 for none), `AttachmentReady` int 0/1 | |
| 12 | RequestRefused | S→C | `Code` int 1-99 (what kind, `#BakaShrot_Refused_*` in `Client/BakaShrot_ErrorCodes.pbi`: what clients act on), `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), `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 |
| 19 | NameResolved | S→C | `Kind` int, `Id` int 0-65535 (the server's), `Name` str ("" if unnamed) | |
| 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, `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
stamped by the server it's pushed to, when the push arrives (its clock, not
the client's), and keeps that time on every server it's replicated to.
## Rules
- **One request at a time.** A client sends one request and waits for its
single answer before the next one.
- **Refuse or abort:**
- **Refuse** (RequestRefused, the connection stays open) for things that
are valid but not allowed: permissions, no message found, too big,
a failed query, a regular client sending replication packets. Each with
a code (`Client/BakaShrot_ErrorCodes.pbi`): NotAllowed, UnknownName,
NotFound, NotReady, TooBig, NoDefaultTopic, InvalidRequest,
DataMismatch, QueryFailed, ServerError. Clients get them from
`BakaShrot_GetLastError()` (the DLL) or `error.code` (Python), with
their own codes (100+) for what never reached the server or broke the
connection.
- **Abort** (the connection is closed) for anything malformed or out of
order: an invalid frame or packet, a packet type that isn't expected at
that point, an answer to a different request, a timeout during the
handshake.
- The client side applies the same rules to the answers it gets.
- **Timeouts:**
- The server gives a client `#BakaShrot_Net_HandshakeTimeout` (10 s) per
handshake step, then waits for requests forever.
- The client side (`Outbound.pbi`) waits `#BakaShrot_Outbound_Timeout`
(10 s) for each answer.
- **The identity is fixed by the handshake.** Requests never carry who sends
them; the server uses the authenticated topic and node. A push picks its
topic, never its node.
## Flows
### Handshake (every connection)
```
client: knows the server's Ed25519 public key (ServerPublicKey),
makes a key pair for this connection
C -> S ClientHello node (ref, the one it writes as) + Base64 public key
+ the public half of the client's pair,
sealed for the server's public key
server: opens it (or aborts: not for this server), the node must
resolve to its id, the key must decode to 32 bytes, and one
[BakaShrot.Client.<name>] must have this Node and list this key
S -> C ChallengeRequest fresh random challenge + nonce, the public half of
the server's pair, and the server's signature of
the transcript (in plain text)
client: the signature checks out with ServerPublicKey (or aborts)
both: the connection's keys, from both pairs (crypto_kx), the
pairs' secrets wiped; everything from here on is encrypted
C -> S ChallengeResponse the client's signature of the transcript, nonce echoed
server: nonce == the one issued, signature valid for the Hello's key
S -> C AuthAccepted status -> Authenticated
```
The transcript both sign (`BakaShrot_HandshakeTranscript`, 208 bytes):
a 16-byte label (`"BakaShrot3 srv"` or `"BakaShrot3 cli"`, zero-padded),
the client's and the server's Ed25519 public keys, the client's and the
server's session halves, the challenge, the nonce.
- The status moves through New → Challenged → Authenticated, or Aborted /
Disconnected (`BakaShrot_ConnectionStatuses`).
- When authenticating, the server also records two things for the
connection:
- Its **permissions**, from the matching client section: `AllowRead`,
`AllowWrite`, `AllowQuery`, and the `PushTopics` / `ReadTopics` filters
(default: its `DefaultTopic`, nothing without one), and that
`DefaultTopic`: the topic of its pushes that don't name one.
- Whether it's a **peer**: its key and node match a
`[BakaShrot.Peer.<name>]`, and then its `AcceptTopics`.
### Client requests
```
PushMessage(t, json) AllowWrite, t in PushTopics ("" = its DefaultTopic,
refused without one), at most
#BakaShrot_MaxMessageSize. JSON or not: stored as
is, SQLite flags it in is_json
-> stored under t and the authenticated node with the
next message id, stamped with now (pushed_at)
-> MessagePushed(id)
GetLatestMessage(t, n) AllowRead, t in ReadTopics -> LatestMessage
GetMessages(t, n, after, AllowRead, t in ReadTopics -> Messages: those above
limit) after, in id order, at most limit, fewer once they
reach ~1 MB (#BakaShrot_MessagesBatchBytes, a
bigger one alone). None isn't a refusal. More = 1
if others follow: ask again after the last id
ResolveName(kind, ref) topics: in PushTopics or ReadTopics, or AllowQuery
-> NameResolved(id, name)
ListNames(kind) topics: those in PushTopics or ReadTopics, all with
AllowQuery -> NamesList(entries)
QueryRequest(sql) AllowQuery -> QueryResult
```
**Raw queries** (`RunReadOnlyQuery()` in `Server/Storage/Storage.pbi`) are kept
read-only by three things:
1. The SQL must start with `SELECT` or `WITH`.
2. It runs on its own fresh connection with `PRAGMA query_only = ON`. Writes
fail, and turning the pragma off only affects that throwaway connection.
3. Only the first statement runs.
Statements with no result columns are refused, and so are results over
10000 rows or too big for one packet. An error while reading the rows
refuses the whole query with SQLite's message, never a partial or empty
result: JSON functions over a row that isn't JSON give "malformed JSON",
add `is_json = 1` to the WHERE (or `CASE WHEN is_json THEN ... END`). PureBasic reports no column types for
SQLite, so values come back as strings.
### Replication (between servers)
Each server opens its own link to every `[BakaShrot.Peer.<name>]`,
authenticates as itself (the peer must list it as a client), and retries
every `PeerRetryDelay` seconds when that fails or the link drops. On its own
link, every `PeerSyncInterval` seconds, starting right away:
```
P -> S SyncStateRequest
S -> P SyncState every name S takes from P (its AcceptTopics and
AcceptNodes for P), their wildcards, and
MAX(message_id) for each topic/node of those, in
S's ids
P: compares with its own state (GetSyncState()), matching by name,
drops what's unnamed on its side, or neither listed by S nor
matching one of S's wildcards (BakaShrot_Names_NoteDropped(), a
no-op for now), and for every pair in its SendTopics and
SendNodes for S that S is behind on (0 for a name S doesn't have
yet):
P -> S ReplicateMessages the topic and node names, the next missing messages
of that pair, in id order, with their original
message ids and pushed_at: up to PeerBatchSize of them, cut short
at about 64 KB (a bigger message goes alone)
S: resolves the names to its own ids, adds the ones a wildcard took,
refuses what it doesn't take (only if its config changed since
its sync state), see Server/Storage/Names.pbi
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
`[BakaShrot.Server]` (default 100, clamped to 1-10000).
- **Size check:** the sender estimates a batch's size with
`#BakaShrot_ReplicateBatchOverhead` + `#BakaShrot_ReplicateMessageOverhead`
per message + the JSON's UTF-8 bytes, and stops adding messages before
it would go over `#BakaShrot_ReplicateBatchBytes` (64 KB, as when that
was the packet limit: short transactions, little memory). A message
bigger than that goes in a batch of its own. It also stops reading rows
from the database once it has about that much (`GetMessagesAfter()`).
- **Both directions** are covered because each server pushes over the link
it opened itself.
- **Only peers may replicate:** a regular client sending a SyncStateRequest
or ReplicateMessages is refused with `Only peers can replicate`.
- **Unexpected packets:** a packet on a link outside a check-in drops the
link.
- **Retention:** each server deletes a topic's messages past its own
`[BakaShrot.Retention]` max age (`Server/Storage/Retention.pbi`), by their
pushed_at. The sync state comes from `node_heads`, which deleting leaves
alone: a server still says it has what it deleted, so peers don't send it
again. What a peer sends already past this server's max age isn't
stored, but counts as received the same way (still acknowledged). A
peer that links later only gets what the others still have.
## Code conventions
- **Encode:** `BakaShrot_<Name>Packet_Encode(*Struct, *OutSize.Integer)` sets
the base fields itself, and returns a new buffer (the caller frees it with
`FreeMemory`) or 0.
- **Decode:** `BakaShrot_<Name>Packet_Decode(*MsgPackData)` returns a new
struct (the caller frees it with `FreeStructure`) or 0. It reads a view
made with `MsgPackWrapMsgBuffer()`, which the caller frees with
`MsgPackFree(*View, #False)`.
- **Linear code:** each field is written or read top to bottom: check its
type, read it, check the error, check its range. No loops, except for
lists such as SyncState's.
- **Which decoder to use:** `BakaShrot_GetPacketType()` reads a received
packet's type, so a handler can pick the right `_Decode`.
## Adding a packet
1. Add its id to `BakaShrot_PacketTypes` in `Commons/Networking/Packets.pbi`.
Never reuse an id.
2. Add `Commons/Networking/Packets/<Name>Packet.pbi`, with its structure
(`Extends BakaShrot_PacketBase`), `_Encode` and `_Decode`, following an
existing one.
3. Include it from `Commons/Networking/Connections.pbi`, and add it to the
flow comment at the top of that file.
4. **Server side:** handle it in `BakaShrot_NetClient_HandleRequest()`
(`Server/Networking/Networking.pbi`), checking the permission or role
first.
5. **Client side:** add a `<Name>String()` procedure to the DLL with its
`A`/`W` exports if it takes strings, a prototype in
`BakaShrot_Client_Prototypes.pbi`, and a tool if useful.
6. Update this document's packet table and flows.
+244
View File
@@ -0,0 +1,244 @@
# Releases - smoke test, 1.0.0, CI/CD
How releases are built and checked, what's missing before a 1.0.0, and what
to keep in mind when the builds move to CI/CD. Related docs:
- `Notes.md`: where things stand, the open items.
- `Design/StorageConcurrency.md`: WAL, `synchronous`, the writer.
- `Design/Cryptography.md`: what the handshake and the encryption protect,
and what they don't.
## Today
`Release.ps1` builds with PureBasic 6.40's C backend (`/OPTIMIZER`) into
`Release\<version>\` and zips it. `<version>` is `-Version`, or
`<date>-<commit>`, with `-dirty` if the tree has uncommitted changes (a
warning, not an error).
Its smoke test, from the release folder, on one server with a throwaway
database:
- generates keys with `BakaShrotGenerateKeyPairs.exe`, writes a server and a client config;
- pushes two messages, reads the latest back by name, reads both with
`BakaShrotGetMessages.exe`, resolves a name, queries them through the `messages`
view with `is_json = 1`;
- if `python` is on the PATH, reads them and pushes one with
`python\bakashrot.py`, then installs the wheel (`python\bakashrot-*.whl`,
built by `Interactors/Python/make_wheel.py`) with pip into a folder and
reads and pushes with it, from elsewhere and with no DLL path;
- pushes a 3 MB attachment with `BakaShrotPushMessage.exe -a` and reads it back
identical with `BakaShrotGetAttachment.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, 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
**Fixed (2026-11-08):** `Libs/redist/x64/vcruntime140.dll` (from Visual
Studio's `VC\Redist` folder, see `Libs/redist/README.md`) is copied next to
the exes by `Release.ps1`, which refuses to build without it, and
`VERSION.txt` gives its version and "Windows 10 or later, 64-bit". Next to
the exe, it's found before an installed one (it isn't a KnownDLL). Still to
check once on a clean Windows (item 1 below).
What it was:
`libsodium.dll` (the official MSVC build) imports `vcruntime140.dll` and the
`api-ms-win-crt-*` DLLs: the **Visual C++ runtime**. The release didn't
ship it and `VERSION.txt` didn't say so: it worked on the build machine only
because the runtime is installed there, on a clean Windows
`BakaShrot_Server.exe`, `BakaShrot_Client.dll` and every tool would fail to
load. Our own exes and `sqlite3.dll` don't need it. The `api-ms-win-crt-*`
ones are the Universal CRT, part of Windows 10 and later.
Checked with: `grep -a -o -i -E "(vcruntime[0-9_]*|msvcp[0-9_]*|api-ms-win-crt-[a-z0-9-]+)\.dll"`
on each binary of the release folder.
## The 1.0.0 smoke test
What `Release.ps1`'s test should also do, by importance. Most of it exists
in `Tests/` already, to be pointed at the release instead.
1. **Run from the extracted zip**, in a fresh folder, not from the release
folder: proves the zip has everything. Once on a **clean Windows**
(Windows Sandbox is enough), which is where the runtime above shows up.
2. **Replication**: two servers from the release, same names with
different ids. Push on A, read it on B by name, same data, same message
id; and the other way around.
3. **Restart, picking up where it was** on its last run:
- kill a server (not a clean stop), start it again on the same database;
- the messages are still there, and the next push to a topic/node gets
the next id, not 1 again or one already used;
- with two servers: push on B while A is down, start A, A catches up on
what it missed, and B gets what was pushed to A before it went down if
B hadn't had it yet.
That's how it's meant to work already, since nothing it needs lives
only in memory: the next message ids are read from the database the
first time a pair is pushed to (`Writer.pbi`), `node_heads` is kept by a
trigger in the same transaction as the messages, and every check-in
with a peer starts from both sync states, read from the databases. A
killed process loses nothing committed, whatever `Synchronous` says
(with `NORMAL`, a power loss or an OS crash can lose the last second). **Tested** by
`Tests/Restart-Test.ps1` (2026-11-09): kills with traffic in flight,
once in the middle of a catch-up, both directions, all hold. With
`BenchServer.exe` (the same server code plus a stop file), not the
release's exe itself.
4. **A clean shutdown**: the release server only stops from its console
(`quit`), so the test force-kills it, and the clean path never runs.
Needs a way to stop it without a console: a stop file like
`BenchServer.exe`'s, or a local admin connection (`Notes.md`, console
commands can't be scripted). Then check it stops within a few seconds,
with its last messages committed. On Linux, SIGTERM does it (2026-11-10,
checked through `docker stop`).
5. **Refusals**:
- an unknown public key, and a known one with the wrong private key:
not authenticated;
- a client given the wrong `ServerPublicKey`: can't connect (tested in
`Tests/wire_check.py`, not against the release);
- a frame over 4 KB before authenticating: cut right away;
- a client reading a topic outside its `ReadTopics`, pushing outside its
`PushTopics`, querying without `AllowQuery`: refused, and still
connected.
6. **`config.example.ini` loads**: fill in keys, start the server from it.
It's documentation, it drifts otherwise.
7. **The server's log is captured and checked**: no "Failed", "invalid",
"unexpected", "too much data" from the clients that are meant to work.
Today its output goes to a hidden console nobody reads.
8. **The data rules**:
- a non-JSON push is stored as is, with `is_json = 0`;
- a 1 MB message reads back whole, on both servers;
- a JSON query over non-JSON rows without `is_json = 1` is refused with
SQLite's error, not answered with no rows (fixed, see below).
9. **Every shipped tool runs once**: `BakaShrotList`, `BakaShrotGetMessages --follow`
(picks up a new push, exits 1 once the server is gone) aren't yet.
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 (5 now) 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).
Order: 1-3 first (the runtime is fixed), they're what a real deployment hits
on day one. Then 5-8, cheap since `Tests/` has most of it. 4 with the
console item.
## Fixed: a JSON query over non-JSON rows answered nothing, silently
Item 8, it came up with every change about non-JSON messages. Fixed on
2026-11-08 (Windows).
**What happened.** Since pushes aren't checked to be JSON anymore, the
`data` table holds both, flagged in `is_json`. SQLite's JSON functions
(`->>`, `json_extract()`, ...) raise an error on a row that isn't JSON
("malformed JSON"), and that ends the query: SQLite doing what it should.
But `RunReadOnlyQuery()` reads the rows with PureBasic's `NextDatabaseRow()`,
which returns `#False` both at the end of the rows and on an error, and
`DatabaseError()` stays empty after it. So the query counted as a success:
`{"rows": []}` for an aggregate (`SELECT COUNT(*) ... WHERE message_data ->>
'$.level' = 'warn'` gave no row at all), or only the rows read before the
first non-JSON one. A wrong answer that looked like a right one.
**The fix** (`RunReadOnlyQuery()`, `Server/Storage/Storage.pbi`): once the
rows end, SQLite itself is asked, with `sqlite3_errcode()` on the
connection's handle (`DatabaseID()`), before `FinishDatabaseQuery()`.
`SQLITE_DONE` (or `SQLITE_ROW`/`SQLITE_OK`) means they really ended,
anything else is an error: the query is refused with `sqlite3_errmsg16()`'s
message, and a hint when it's about JSON:
Query failed: malformed JSON (a row isn't JSON: add is_json = 1 to the WHERE)
Why this one:
- **Safe:** nothing else changes. The rows are still read by PureBasic, the
query isn't touched, only what happens once they end. A false alarm
would refuse a good query, visibly; it can't hide a bad one anymore.
- **Small:** two functions of the same `sqlite3.dll` PureBasic loaded, like
`Writer.pbi` does, loaded once under a mutex. If they can't be found,
every query is refused rather than unchecked.
- **General:** any error that cut the rows short is caught the same way (a
write stopped by `query_only` in `DELETE ... RETURNING` too), not only
JSON. It replaces the `DatabaseError()` check, which may be shared
between threads anyway.
Not done: having the server add `is_json = 1` to queries itself. It would
mean rewriting arbitrary SQL (subqueries, CTEs, joins), and a query that
wants the non-JSON rows too would get the wrong answer the other way.
**Queries still need the clause** (or `CASE WHEN is_json THEN ... END`) to
run JSON functions over mixed rows: they're refused instead of wrong now.
`CASE WHEN` is the guaranteed form: with `AND is_json = 1`, SQLite doesn't
promise to test that term first. It does today for these queries, and if a
plan ever didn't, the query would be refused now, not answered wrong.
**Not on Linux:** PureBasic's own SQLite is linked in there, not reachable
this way, so it keeps the `DatabaseError()` check that misses it. To do if
it's ever built there: `ImportC` the two functions, or read the rows with
SQLite's API like the writer.
**Tested:** `Tests/BigMessages-Test.ps1`: an aggregate and a row-by-row
SELECT over mixed rows are refused with "malformed JSON"; non-JSON rows
read without JSON functions, `CASE WHEN is_json`, a query with really no
rows and a plain SQL error behave as before.
## Before calling it 1.0
Not smoke-test items, but what the "1.0" label would promise. From
`Notes.md`'s open items:
- ~~Clients and peers can't verify the server's identity.~~ Fixed
(protocol 3, `Design/Cryptography.md`).
- ~~No encryption, no per-packet authentication after the handshake.~~
Fixed (protocol 3).
- Messages aren't signed by the node that first wrote them: a peer is
trusted with what it replicates (`Design/ReplicationIssues.md` #3).
- ~~`synchronous = NORMAL`: the last commits can be lost on a power loss.~~
Decided: `[BakaShrot.Server] Synchronous`, `FULL` by default
(`Design/StorageConcurrency.md`).
Either they're fixed, or they're documented limits of 1.0 (or it's a 0.9).
## For CI/CD
Notes for when the builds move to a pipeline.
- **Toolchain:**
- PureBasic isn't freely downloadable: a self-hosted Windows runner with
a licensed install, or a private image. Compiler paths are parameters
(`Build.ps1 -Compiler`, `Release.ps1 -Compiler`), default to
`C:\Program Files\PureBasic_573\...` and `..._640\...`.
- Two compilers are in use: 5.73 for `Build\` and the tests, 6.40's C
backend for releases. Decide whether CI tests the release build (it
should, it's what ships), or both.
- Check out with submodules (`Includes/PB-MessagePack`).
- `Libs/` holds the libsodium and SQLite zips: pin them and check their
hashes in the pipeline.
- **Scripts that need changes first:**
- `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-12416 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
and cipher tests) and fails if any fails. Today each is run by hand.
- The release server needs a console, or it stops right away (no
console input). The smoke test gives it a hidden window: check that
works on the runner (a service account may not get a console), or do
item 4 first.
- **Environment:**
- Exes run from temp folders are blocked by the antivirus here, the
tests run them from `Build\`. A runner may differ either way.
- A clean-machine job, without the Visual C++ runtime, to catch missing
DLLs (see above).
- Python: 64-bit, the oldest claimed version (3.8) and the latest.
- **Versions and artifacts:**
- Releases from tags (`v1.0.0` -> `-Version 1.0.0`), refusing a dirty tree.
- Artifacts: the release zip, and a source zip. Not `Build\`.
- **Benchmarks** (`Tests/Bench/`): too noisy and long for every build. A
nightly or on-demand job, compared to a stored baseline with
`Compare-Runs.ps1`, failing only on a big drop.
- **Linux:** `Libsodium.pbi` and the writer have Linux paths, never built
or tested. A later job, once wanted.
+174
View File
@@ -0,0 +1,174 @@
# Replication - known issues
How it works now: see the top of `Server/Networking/Peers.pbi`. In short, every
`PeerSyncInterval` seconds a server asks each linked peer for its sync state
(the highest message id per topic/node id), and sends it the messages it's
behind on, with their original ids. Each peer does the same over its own link.
Issues below are roughly ordered by how much they matter.
## 1. Drift: the same message id with different content (ruled out by config)
**The rule: a node pushes to one server.** Each client node has its
`[BakaShrot.Client.<name>]` section (its `Node`) on one server only, the
one it pushes to; the other servers get its messages by replication. Then
every topic/node pair has a single writer and this can't happen. Reading
from any server is fine, only pushing matters. Breaking the rule isn't
detected: it's the config's to keep.
**When it would happen:** the same topic/node id written to on two
servers, for example a client node registered on both, pushing to each
while they can't reach each other.
**What happens:** both servers are at `1:2#1`, the link drops, then:
| | Server A | Server B |
|---|---|---|
| Before | 1 | 1 |
| Client pushes to both | 1, 2a, 3a | 1, 2b |
| Once relinked | A is ahead, sends `#3a` | B isn't ahead, sends nothing |
| Result | 1, 2a, 3a | 1, 2b, 3a |
- Only the max id is compared, so `#2a` vs `#2b` is never noticed.
- If both had sent the same id, `INSERT OR IGNORE` would keep the local one
and silently drop the other.
- The servers end up partially resynced, with a mixed history for that pair.
**Possible fix, maybe someday:** authoritative servers. Each topic/node id
gets one server that's allowed to assign its message ids, and the others only
replicate it. Pushes for a pair not owned locally are refused, or forwarded.
A cheaper half-measure: detect drift by also comparing a hash of each
message (or of a range of them), and at least log it.
## 2. ~~The peer isn't verified~~ (fixed 2026-11-08, protocol 3)
It was: the handshake only proved the connecting side, the `PublicKey` in a
`[BakaShrot.Peer.<name>]` section was never checked, so whatever answered on
the peer's address got this server's messages pushed to it.
Now a link's Hello is sealed for the peer section's `PublicKey`, and the
peer must sign the handshake with the matching private key, or the link
fails; the link is encrypted (`Design/Cryptography.md`). A missing or
invalid `PublicKey` stops the server at start. The section's `Topic` and
`Node` are still only checked when the peer links to here.
## 3. Peers are trusted completely
A connection that authenticated with a peer's identity and key can replicate
messages for any topic/node id the receiver replicates, with any content.
Messages carry no proof of who first wrote them, so a compromised or buggy
peer can inject or overwrite history for nodes it doesn't own. (Overwrite
only in the sense of issue 1: it can't replace an id that's already stored.)
**Fix:** sign each message with its originating node's key when it's first
stored, keep the signature with it, and verify it on replication. That needs
every server to know the public key of every node it replicates.
## 4. Database concurrency (fixed)
**Fixed 2026-11-06:** every link thread and client thread now has its own
database connection, see `Design/StorageConcurrency.md`. Kept below for the
record.
The link threads used to read the database with the same unlocked handle as
the client threads.
**Seen happening** (2026-11-06, benchmark with `PeerBatchSize = 1`):
1. Server 1's link thread was reading the messages to send.
2. At the same time, server 1's thread for server 2's incoming link was
reading the sync state for server 2's check-in.
3. Both went through the same handle, so a read came back empty while
messages were still left. Server 1 logged
`Sent 1424 messages ... it had up to #0` for a backlog of 5000, and the
check-in ended there.
The next check-in picked up where it stopped, so nothing was lost here. But
the same collision during a write could have stored wrong data.
## 5. Gaps aren't detected
Only `MAX(message_id)` is compared. If a server has `1, 2, 5` for a pair (say
`3` and `4` were refused midway through a check-in), it reports `5` and never
gets `3` and `4`. Messages are sent in order and the sending stops at the
first refusal, so this needs something unusual, but nothing repairs it.
**Fix:** send a count with the max (`COUNT(*) = MAX` means no gaps), and fall
back to comparing id ranges when they differ.
## 6. Speed: batched since, the per-batch overhead remains
**Benchmarks** (2026-11-06, both servers on localhost, PureBasic 5.73 x64,
SQLite 3.54.1). The same 5000 messages of ~28 bytes and 1000 of ~4 KB, sent
from scratch:
| Version | 5000 small | 1000 x 4 KB |
|---|---|---|
| One message per packet (before batching) | 63.6 s, ~79 msg/s | 12.2 s, ~82 msg/s |
| `PeerBatchSize = 1` | ~69-87 msg/s | 12.0 s, ~83 msg/s |
| `PeerBatchSize = 100` (default) | 0.67 s, ~7500 msg/s | 0.94 s, ~1070 msg/s, ~4.3 MB/s |
| `PeerBatchSize = 1000` | 0.11 s, ~45000 msg/s | 1.48 s, ~680 msg/s |
**Where the per-batch time goes,** measured before batching:
- **~3.8 ms is SQLite**, one transaction synced to disk. The same inserts
inside one transaction take 0.014 ms each (5000 in 71 ms). Hence one
transaction per batch.
- **The rest is polling.** Both ends wait for packets in `Delay(5)` loops
(5.5 ms each on Windows, `Delay(1)` is 1.6 ms), and each batch waits for
its acknowledgement before the next one, so it pays a few of those per
round trip.
**Big messages** don't gain from batch sizes over ~16: only that many 4 KB
messages fit in a ~64 KB batch (`#BakaShrot_ReplicateBatchBytes`). Since
2026-11-08 a batch stops reading rows once it has that much, so a big
`PeerBatchSize` no longer reads rows it then can't send.
**Further fixes, if needed:**
1. Keep the rows that didn't fit for the next batch instead of reading them
again.
2. ~~Wake the waiting thread when data arrives instead of polling with
`Delay(5)`.~~ Done 2026-11-07: client threads sleep on an event the
listener sets (`Commons/Threading/Signal.pbi`), the listener and the
outbound side sleep in `select()` (`Commons/Networking/SocketWait.pbi`).
3. Send the next batch before the previous one is acknowledged (a window).
4. ~~WAL mode~~ Done 2026-11-07, see `Design/StorageConcurrency.md`.
**Since then** (2026-11-07, `Tests/Bench/Bench-Replication.ps1`, 4 servers in
a Y): the hub relays up to ~5700 msg/s of pushes to its leaves without
falling behind, sending at ~38000 msg/s while a catch-up runs. The lag is
now just the check-in wait, 4-6 s of pushes at every load (two check-ins for
leaf to leaf). A shorter `PeerSyncInterval` is what would lower it.
~~**A message that's too big for a batch isn't replicated.**~~ Fixed
2026-11-08: pushes are capped at `#BakaShrot_MaxMessageSize`, 4 KB under the
16 MB packet limit, so one always fits in a batch of its own.
## 7. Sync state size limit
The whole sync state must fit in one packet: 16 MB since 2026-11-08 (was
64 KB, roughly 4000 topic/node pairs), so the counts are what limits it now,
65536 topics, nodes and pairs (`SyncStatePacket.pbi`). The replicated topics are also sent as a list, and
`ReplicatingTopicIds = 0-65535` expands to 65536 entries, which doesn't fit.
**Fix:** send ranges instead of expanded lists, and page the pairs (for
example per topic).
## 8. Two links per pair of servers
With two servers listing each other as peers, there are two connections, and
each one is only used by its opener to push. That's what makes both
directions work, but it doubles the connections and the check-ins. Fine for
now. If it ever matters, one link could carry both directions.
## 9. Messages for topics a server doesn't replicate
The receiver lists the topics it replicates, and the sender only sends
those, so they're never sent. But a batch that arrives for another topic
anyway is refused, and that stops the pair's catch-up for that check-in. It only happens if the two servers disagree about the list
mid-check-in, for example after a config change.
## 10. ~~Replicated messages aren't validated~~
Moot since 2026-11-08: pushed messages aren't checked to be JSON either,
both are stored as is and flagged by `is_json`.
+179
View File
@@ -0,0 +1,179 @@
# Storage concurrency
Status (2026-11-07): **one connection per thread, WAL mode, a write mutex,
group commit, and a single writer connection with prepared statements are
done.** Full benchmark history: `Tests/Bench/Results-2026-11-07.md`. Ideas
not done yet: `Design/Suggestions.md`.
## The writer (2026-11-07, `Server/Storage/Writer.pbi`)
- **Every write goes through one connection,** opened by
`OpenStorageWriter()` when the workers start and closed by
`CloseStorageWriter()` once they're stopped (`Server/Root.pbi`). It's the
one exception to the rule below: shared, but only ever used while holding
the write mutex, so never by two threads at once.
- **Prepared statements, kept open,** through SQLite's own API
(`sqlite3_prepare16_v2`, `sqlite3_bind_*`, `sqlite3_step`), from the
same `sqlite3.dll` PureBasic loads: `DatabaseID()` is its `sqlite3`
handle. PureBasic prepares a statement again on every call. Windows only,
elsewhere the writer falls back to PureBasic's functions.
- **The next id of every topic/node id in memory,** instead of a
`MAX(message_id) + 1` in every insert: read from the database the first
time, raised by replicated messages, forgotten on any rollback. Only right
while this writer is the only one writing.
- **Checkpoints in a background thread,** every second, in PASSIVE rounds
that don't block anything, then a short one under the write mutex once
little is left, so the WAL can start over. The writer still checkpoints by
itself past 10,000 WAL frames, as a backstop when the thread can't keep up
(flat out). Without that backstop the WAL reached 700 MB and Windows
throttled the writes, up to 5 s for a push.
- **`node_heads`,** the highest message id of every topic/node id, kept by a
trigger on `data` (so even `BenchSeed` keeps it right). The sync state is
read from it: 0.5 ms instead of 167 ms at 2.4M rows, on every check-in.
Schema: `Server/Storage/db_schema_v3.dbml` (now `db_schema_v4.dbml`)`.
- **Measured:** ~25,700 -> ~34,300 msg/s for 4 servers, ~38,400 built with
PureBasic 6.40's C backend. p99 at 10 nodes x 50 msg/s: 13.6 -> 0.8 ms.
## WAL and the write mutex (2026-11-07)
- **WAL mode,** set by `SetupStorageDatabase()` (stored in the file), with
the config's `synchronous` on every connection (see below). Readers no
longer block the writer: a 0.5 s raw query used to stall pushes for
seconds and once made one fail with "database is locked", now pushes run
next to it at full speed.
- **`synchronous` is `[BakaShrot.Server] Synchronous`** since 2026-11-09,
`FULL` by default (it was `NORMAL`, fixed). The root sets
`BakaShrot_Storage_Synchronous` (`Storage.pbi`) before it opens any
connection. `OFF` is refused (a power loss could corrupt the file),
`EXTRA` too (the same as `FULL` in WAL mode, it only adds a directory
sync for the other journal modes).
- `FULL`: every commit flushes the WAL. An acknowledged push survives a
power loss or an OS crash. The flush is per transaction, so a group
commit's pushes share it.
- `NORMAL`: the WAL is only flushed at checkpoints (about every second,
`Writer.pbi`). The file can't get corrupted, but the last second or so
of commits before a power loss or an OS crash can be lost. Those
messages were acknowledged and maybe already replicated, so their ids
could be handed out again: drift (`ReplicationIssues.md` #1).
### Measured (2026-11-09)
`Bench-Replication.ps1 -Ramp "1x0,10x0,10x20" -Parts Ramp -Synchronous ...`,
4 servers in a Y, totals of the 4, one run each (±5-10%). On a VM whose
virtual disk flushes in 0.60 ms (p99 0.78 ms).
| | OFF | NORMAL | FULL | EXTRA |
|---|---|---|---|---|
| 1 pusher per server, flat out: msg/s | 28,785 | 22,595 | 5,100 | 5,026 |
| ... push p50 / p99 | 0.1 / 0.8 ms | 0.1 / 0.8 ms | 0.7 / 5.3 ms | 0.7 / 3.3 ms |
| 10 pushers per server, flat out: msg/s | 42,854 | 33,870 | 17,207 | 17,763 |
| ... push p50 / p99 / max | 0.6 / 4.8 / 95 ms | 0.5 / 3.3 / 1,113 ms | 1.6 / 9.3 / 123 ms | 1.6 / 8.7 / 129 ms |
| 800 msg/s steady: push p50 / p99 | 0.2 / 0.5 ms | 0.2 / 0.9 ms | 0.9 / 5.0 ms | 0.8 / 4.6 ms |
| Lost on a power loss / OS crash | the file may be corrupted | ~1 s of acknowledged pushes | nothing acknowledged | same as FULL |
No failed pushes, replication kept up in every case. `FULL`'s cost is the
disk's flush time: one client pushing one message at a time gets about
1 / (flush + 0.15 ms) pushes/s, ~1,300/s here; many clients share flushes
through the group commit, so the total drops much less (half here). On a
server SSD with power-loss protection a flush is far under 0.1 ms (close
to `NORMAL`), on a consumer SSD 1-5 ms, on a hard disk ~10 ms (~100/s for
one sequential client): time one on the target machine to know.
- **`BakaShrot_Storage_WriteMutex`** around every write. A connection that
finds the database locked sleeps in SQLite's busy handler (1, 2, 5, 10...
ms) and retries; with 10+ threads pushing, that's where the time went, and
10 nodes per server pushed less than 5. Queued on the mutex, the next one
writes as soon as the lock is free. The busy timeout still covers other
processes.
- **Measured** with `Tests/Bench/Bench-Replication.ps1` (4 servers in a Y,
~200-byte messages, i5-13500, all on localhost), along with the wake-ups
instead of `Delay()` polling (`ReplicationIssues.md` #6):
| | Before | After |
|---|---|---|
| Cluster push ceiling, 5 / 10 nodes per server | ~955 / ~900 msg/s | ~5770 / ~5730 msg/s |
| Push latency p50 / p99, 10 nodes x 50 msg/s | 18 / 490 ms | 0.4 / 5 ms |
| Indexed query (latest message) | 6-12 ms | ~0.5 ms |
| Pushes while a 0.5 s query loops | 323 of 400 msg/s, max 5.1 s, 1 failure | 396 of 400, max 17 ms |
That ceiling turned out not to be the database, but the `PrintN()` logging
every push (~0.4 ms each, serialized): see below.
## Group commit (2026-11-07)
- **`InsertNextMessage()`** queues the push (`BakaShrot_Storage_Queue`),
then takes the write mutex. Whoever holds it writes every queued push in
one transaction (up to `#BakaShrot_Storage_MaxGroupSize`), so the pushes
that were waiting find theirs done. No extra thread: the busier it gets,
the bigger the groups. Each push still returns once committed.
- **`[Storage]` log line** every 10 s while pushes come in: pushes/s,
pushes per transaction, ms per push, and how busy the writes are.
- **No more log line per push, read or query** (`#BakaShrot_Net_LogRequests`
in `Networking.pbi`): that `PrintN()` was what capped a server at ~2,400
pushes/s.
- **Measured:** a single server ~2,400 -> ~12,000 pushes/s, the cluster of 4
~5,800 -> ~25,700 msg/s, 2.5-9 pushes per transaction when saturated.
The writes are now the limit again (70-90 % busy at 0.07-0.11 ms per push).
- **Open:** p99 at moderate load went up (0.7 -> 8-18 ms). Suspect: a WAL
checkpoint running while holding the write mutex.
## The rule
**Never share a database handle between threads.** The `SetDatabase*()`
parameters and the query results belong to a handle, so two threads using one
overwrite each other's. That used to happen: a peer link once read an empty
result while 3500 messages were left to send, see
`Design/ReplicationIssues.md`, issue 4.
Every thread that touches the database opens its own connection with
`OpenStorageDatabase()` and closes it when it ends:
| Who | Opens | Closes | Where |
|---|---|---|---|
| A client thread | once its client is authenticated | when the thread ends | `BakaShrot_NetClient_Thread()`, `Server/Networking/Networking.pbi` |
| A peer link thread | when the thread starts | when the thread ends | `BakaShrot_PeerLink_Thread()`, `Server/Networking/Peers.pbi` |
| A raw query | for the query, read-only | right after | `RunReadOnlyQuery()`, `Server/Storage/Storage.pbi` |
| The root | at start, and on restart | on restart and at the end | `Server/Root.pbi` |
The root's connection is only used for setup, and while the workers are
stopped (vacuum, restart). See `Server/Root.pbi`.
## What makes several connections work
- **Busy timeout.** Each connection sets
`PRAGMA busy_timeout = #BakaShrot_Storage_BusyTimeout` (5000 ms), in
`OpenStorageDatabase()`. SQLite allows one writer at a time across
connections. Without it, a write fails at once with "database is locked"
while another connection writes. With it, the write waits its turn.
- **Atomic next id.** `InsertNextMessage()` is a single statement:
```sql
INSERT INTO data (topic_id, node_id, message_id, message_data)
SELECT ?1, ?2, COALESCE(MAX(message_id), 0) + 1, ?3
FROM data WHERE topic_id = ?1 AND node_id = ?2
RETURNING message_id
```
Nothing can run between reading `MAX` and inserting, even from another
connection. The UNIQUE `(topic_id, node_id, message_id)` constraint stays
as a safety net.
- **`BEGIN IMMEDIATE` for replicated batches** (`InsertReplicatedMessages()`).
It takes the write lock up front, waiting for it like any write, instead
of a deferred transaction that could fail midway when upgrading to a write
lock.
**Tested:** 8 connections pushing 100 messages each to the same topic/node
id at once, while two servers replicated. 800 pushes in 6.2 s, no failures,
ids exactly 1-800 on both servers.
## Left for later
- **What happens when the busy timeout runs out.** The statement fails, so
the push or batch is refused and retried at the next check-in for
replication. Fine at current loads; decide later whether pushes should
retry.
- ~~**Whether PureBasic's `DatabaseError()` is per thread**~~: it is, in
thread-safe mode (`/THREAD`), checked 2026-11-09 with 5.73 and 6.40: two
threads failing on their own connections 20,000 times each never saw the
other's message. `sqlite3_errmsg16()` on the connection gives the same
text. (`RunReadOnlyQuery()` still asks SQLite on Windows, for the errors
`DatabaseError()` doesn't report at all, see `Design/Release.md`.)
- **A single storage thread with a job queue,** only if writes ever become
the bottleneck. SQLite only has one writer anyway.
+123
View File
@@ -0,0 +1,123 @@
# Suggestions, not done yet
Improvements that came out of the 2026-11-07 benchmarks
(`Tests/Bench/Results-2026-11-07.md`), kept aside on purpose. The first two
are bigger changes, worth it when the use case needs them, the rest are
smaller.
## 1. Several pushes in flight per connection
**Today:** a client sends a `PushMessage`, waits for its `MessagePushed`,
then sends the next. One node can push at most once per round trip:
| Round trip | Most pushes/s per node |
|---|---|
| localhost, now | ~2,000-3,000 |
| LAN, 0.5 ms | ~2,000 |
| WAN, 50 ms | ~20 |
The server side doesn't care much, it groups pushes from every connection
anyway. This is about one node, or few nodes, far from their server.
**What it entails:**
- **Protocol.** Let a client send up to W pushes before the first answer.
TCP and the one thread per connection already keep them in order, and the
answers come back in the same order, so the Nth answer belongs to the Nth
push. Still, add a `RequestId` (client-chosen, echoed in `MessagePushed`
and `RequestRefused`) so a client can match answers without counting, and
so a desync is detectable. Old clients send no `RequestId` and keep
working one at a time. See `Design/Packets.md` for how to add a field.
- **Server inbox.** It holds at most two of the biggest packets
(`BakaShrot_Inbox_MaxSize()`), anything more aborts the connection as
"sent too much data". Since big packets (2026-11-08) that's ~32 MB once
authenticated, plenty for a window of small pushes, but a window of big
ones still needs backpressure: stop reading that client's socket while its inbox is full,
so TCP slows it down. PureBasic's `NetworkServerEvent()` keeps reporting
data that isn't read, so backpressure means the listener has to skip that
client's events without spinning: easiest is a per-client "full" flag,
with the listener not calling `ReceiveNetworkData()` for it and leaving
it out of its `select()` set until the client thread drains its inbox.
- **Server thread.** Take every complete packet in the inbox, queue all the
pushes in the writer at once (`BakaShrot_Storage_Queue`), then send the
answers. One connection then fills a whole group commit by itself.
- **Client DLL.** Keep `BakaShrot_PushMessage()` as is (synchronous, W=1).
Add an asynchronous variant for those who want it, without callbacks
since the DLL is used from other languages:
`BakaShrot_PushMessageAsync(Json)` returns a local sequence number,
`BakaShrot_GetPushResult(Sequence)` / `BakaShrot_WaitPushes()` collect the
ids or the refusals. The DLL holds at most W unanswered pushes, the next
call waits for room.
- **Semantics.** Each push is still independent: a refused one doesn't stop
the next ones, the caller gets one result per push. Ids are still handed
out in send order per node.
- **Bench.** `BenchClient` gets a window per pusher, to measure W = 1, 4,
16, ideally with a simulated latency (or the servers on another machine).
**Effort:** medium. Packets, DLL API, the server's inbox and thread loop.
The inbox backpressure is the delicate part.
## 2. Replication: windowed batches, several sockets per link, check-ins on demand
**Today,** per peer link: one connection, a check-in every
`PeerSyncInterval` (5 s) or so, then for each topic/node id the peer is
behind on, one batch of up to `PeerBatchSize` messages at a time, waiting
for its acknowledgement before the next, one pair after the other. The
benchmarks show it keeps up (the hub relays ~25,000+ msg/s), but the lag is
the check-in wait: 4-10 s of pushes, two check-ins from leaf to leaf.
**What it entails, cheapest first:**
1. **Check-ins on demand.** The writer signals (`Commons/Threading/Signal.pbi`)
when it committed something, and the link threads check in as soon as
there's something new, at most every `PeerMinSyncInterval` (say 100
ms), and still every `PeerSyncInterval` when idle. Cheap since the sync
state is now read from `node_heads`. Lowers the lag from seconds to
about the minimum interval plus the relay through the hub. Biggest gain
for the least work.
2. **A window of batches.** Send up to W batches before waiting for the
first acknowledgement, acknowledged in order. On a refusal, stop, and the
next check-in starts again after the last acknowledged one.
- **Needed first: the receiver must refuse a gap.** Today a batch is
stored whatever its first id, with `INSERT OR IGNORE`. With a window,
batch 2 could be stored after batch 1 was refused, leaving a gap that
the max-only sync state never repairs (`ReplicationIssues.md` #5).
Refuse a batch whose first id isn't the pair's head + 1, which
`node_heads` (or the writer's id cache) makes a cheap check.
- The same inbox limit as above: two packets. A peer connection needs a
bigger inbox, or the backpressure.
3. **Several sockets per link.** `PeerConnections = N` in the peer's
section: N connections, N threads on both ends, each one checking in and
catching up its share of the topic/node ids (for example
`(TopicId * 65536 + NodeId) % N`). A pair always goes over the same
socket, which keeps its messages in order. Catch-ups of different pairs
then run in parallel instead of one after the other. On the receiving
side, the batches of the N threads queue on the write mutex: they could
join the pushes' group commit (one transaction for whatever batches and
pushes are waiting) instead of one transaction each.
4. **One connection for both directions** (`ReplicationIssues.md` #8), if
the number of connections ever matters.
**Effort:** 1 is small, 2 is medium (mostly the gap check and the inbox), 3
is medium (config, threads, partitioning), 4 is larger (both ends of the
protocol change).
## 3. Smaller ones
- ~~**Decide on `synchronous = NORMAL`**~~: done 2026-11-09, a config
option (`Synchronous`), `FULL` by default, measured in
`Design/StorageConcurrency.md`.
- **`Build.ps1`:** the compiler path and `-Compiler` are fixed (2026-11-07),
but the `Libs\` zips for libsodium and SQLite are gone: it only works while
the extracted DLLs are still in `Libs\*d`.
- **Benchmark on two machines:** the servers on one, `BenchClient` on the
other. Flat out, the load generator uses ~85 % of a core on the same
machine, and the servers compete with it for the CPU and the disk.
- **The WAL at full speed:** flat out, each server writes ~25,000 WAL
frames/s, and the checkpoints can't keep it small, so the writer falls
back to checkpointing by itself past `#BakaShrot_Storage_WalBackstopFrames`
(the worst push goes up to ~0.7 s). A bigger page size, or fewer indexes
(is `idx_data_message_id` needed?), would write fewer pages per push.
- **Full-table JSON queries** grow with the data (~0.45 ms per 1,000 rows).
If some JSON field gets queried often, a generated column with an index
on it (like the `msg_type` noted in `db_schema_v4.dbml`) makes it a lookup.