mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Got close to the final version
comitting Claude's code before the last mile improvements
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
# 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/KeyGen`. |
|
||||
| `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. |
|
||||
|
||||
- **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/KeyGen`, which `Build.ps1` runs on every build.
|
||||
- **Wiping:**
|
||||
- Wiped from memory after use: KeyGen; 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
|
||||
identity (topic, node), 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>]` lists both this key and this
|
||||
identity.
|
||||
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.
|
||||
@@ -0,0 +1,313 @@
|
||||
# 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 | `Server/Networking/Peers.pbi` |
|
||||
| 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` |
|
||||
|
||||
## 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` (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).
|
||||
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 the
|
||||
config can name them (`[BakaShrot.Topics]`, `[BakaShrot.Nodes]`). 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.*`) 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 | `ClientTopic` str (ref), `ClientNode` str (ref), `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 | 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, `JsonData` str | |
|
||||
| 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) and `JsonData` str | 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`) and `JsonData` str | |
|
||||
|
||||
## 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.
|
||||
- **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 identity (topic and node refs) + 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 refs must
|
||||
resolve to its ids, the key must decode to 32 bytes, and one
|
||||
[BakaShrot.Client.<name>] must list both this key and this identity
|
||||
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: the topics of its `Identities`).
|
||||
- Whether it's a **peer**: its key and identity match a
|
||||
`[BakaShrot.Peer.<name>]`, and then its `AcceptTopics`.
|
||||
|
||||
### Client requests
|
||||
|
||||
```
|
||||
PushMessage(t, json) AllowWrite, t in PushTopics ("" = own topic), 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 -> 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: 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
|
||||
```
|
||||
|
||||
- **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.
|
||||
|
||||
## 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.
|
||||
@@ -0,0 +1,235 @@
|
||||
# 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 `KeyGen.exe`, writes a server and a client config;
|
||||
- pushes two messages, reads the latest back by name, reads both with
|
||||
`GetMessages.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 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.
|
||||
|
||||
## 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, even with `synchronous =
|
||||
NORMAL` (only a power loss or an OS crash can). **Not tested against
|
||||
the release yet**, `Names-Test.ps1` restarts a server but doesn't check
|
||||
these.
|
||||
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.
|
||||
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**: `ListNames`, `GetMessages --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 (3) 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,
|
||||
decide if that's fine (`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-12407 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.
|
||||
@@ -0,0 +1,168 @@
|
||||
# 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 (accepted for now)
|
||||
|
||||
**When:** the same topic/node id is written to on two servers, for example
|
||||
when a client identity is registered on both and pushes to each while they
|
||||
can't reach each other. This is a configuration issue that """shouldn't"""
|
||||
happen in real use.
|
||||
|
||||
**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`.
|
||||
@@ -0,0 +1,148 @@
|
||||
# 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
|
||||
`synchronous = NORMAL` on every connection (`#BakaShrot_Storage_Synchronous`
|
||||
in `Storage.pbi`). 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.
|
||||
- **The tradeoff of NORMAL:** commits are only synced at checkpoints. The
|
||||
file can't get corrupted, but the last 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). Set it to `FULL` to sync every commit again.
|
||||
- **`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** in thread-safe
|
||||
mode. If it's shared by the whole program, an error message could show up
|
||||
in the wrong thread's log or refusal. The data isn't affected.
|
||||
`RunReadOnlyQuery()` only checks it after reading the rows on Linux, where
|
||||
it could refuse a valid query because of another thread's error. On
|
||||
Windows it asks SQLite instead (`sqlite3_errcode()` on its own
|
||||
connection), 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.
|
||||
@@ -0,0 +1,125 @@
|
||||
# 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`** (`#BakaShrot_Storage_Synchronous`):
|
||||
the last commits before a power loss or an OS crash can be lost, and their
|
||||
ids handed out again (drift). With group commit, `FULL` costs one sync per
|
||||
transaction, not per push, so it may cost much less than it used to: worth
|
||||
one benchmark run before deciding.
|
||||
- **`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.
|
||||
Reference in New Issue
Block a user