Repository navigation
Harden wire/zlib parsing, fix delivery/storage bugs, and share DB pool - #54
Conversation
Review findings to remediateReviewed at 1. Shared DB pool can be starved by the sender (regression)Where: Problem: The new process-wide pool is capped at 48 connections. The sender runs up to Failure scenario: 48 or more pending (msg, domain) targets in flight at once, for example a backlog after an outage or a slow or unreachable peer. Those goroutines take every connection in the pool. Every inbound On Fix: inbound and indicator DB access must not be starved by long sender transactions. Either:
Please add a test that fails if inbound store calls block while the sender has more deliveries in flight than the pool has connections. 2. DNS lookup timeout defeats resolver failover (regression)Where: Problem: The non-DNSSEC path now wraps Failure scenario: the first nameserver in
On Fix: make the overall deadline for this path larger than per-attempt timeout × attempts × servers (a separate constant of 15-20s is reasonable), or drop the overall cap and rely on the resolver's own bounds. Keep the 5s value for the DNSSEC 3.
|
…ut, verify FinalizeBatch hash, fix attachment reject precedence, deduplicate updateRecipient
|
Addressed all 5 review findings in
|
markmnl
left a comment
There was a problem hiding this comment.
Checked 9e1956f against the five findings above and read the rest of the diff independently; 0dc188f on top of it only changes a test. All five are fixed and I found nothing blocking. One note inline on the sender pool size.
The five findings
- Sender pool:
findPendingTargets,deliverMessageandmarkLocalDeliveredusegetSenderDB(); inbound handlers and indicators stay ongetDB(). A stalled peer can no longer take connections from the receive path. - Resolver timeout: the non-DNSSEC path has 20s overall; the 5s value stays per server on the DNSSEC clients.
FinalizeBatch: both branches are back to the hash-checkedUnmarshalPrepared, and the snapshot query selectssha256again. The logic now matchesmainline for line.- Reject precedence: the in-loop size checks are gone; the
uint64totals are checked after all attachment headers are validated. updateRecipient: two statements, withmsg_add_tostill scoped bybatch_id.
Checked beyond that
- Wire encoding: the rewritten
Header.Encodeproduces byte-identical output tomain's across 200,000 random headers (all flag combinations, pid, add-to, attachments). I did this as a throwaway differential test because the fmsg-docker suite runs this branch on both hosts and would not catch an encoding change that is self-consistent. - Indicators:
subjectsOfreusing the first batch header is equivalent to the droppedoriginalFromBatchquery (same filter and order). preparePart: the rename into place cannot overwrite anything, sincedstis inside a directory created for that message.go vetpasses andgo test -race ./...at0dc188fpasses with the DB-backed tests enabled against a throwaway PostgreSQL 17 (172 pass, 0 skipped), including the new regression tests for findings 1 to 5.- The fmsg-docker suite passes 16/16 with
9e1956fon both hosts, together with the other threereview/perf-and-reliabilitybranches.
Minor, no change needed
- Shutdown stops accepting and returns; in-flight exchanges and deliveries are cut when the process exits, as on
mainwhere the signal simply killed it. Deliveries are retried after restart. A bounded wait for in-flight handlers would make it a drain.
| const ( | ||
| dbMaxOpenConns = 48 | ||
| dbMaxIdleConns = 16 | ||
| senderDBMaxOpenConns = 32 |
There was a problem hiding this comment.
This is now the real ceiling on outbound concurrency. deliverUnit holds one connection from this pool for the whole exchange, so at most 32 deliveries run at once whatever FMSG_MAX_CONCURRENT_SEND says (default 1024, and the README still describes it as the limit). The remaining goroutines queue in db.Begin() while holding their semaphore slot.
Where it shows: a backlog for an unreachable domain. Each attempt holds a connection for the 10s dial per IP, so 1,000 pending messages for a dead peer occupy the pool for about five minutes, and deliveries to healthy domains wait behind them. findPendingTargets shares the pool, so the poll waits too.
main was not better in principle (one uncapped pool per delivery, bounded only by PostgreSQL's max_connections), so I would not block on this. Options:
- Size the pool from configuration, e.g.
min(MaxConcurrentSend, FMSG_SENDER_DB_MAX_CONNS), and document that this is the effective limit. - Note in the README that fmsgd can now open up to 80 connections (48 + 32) against a default
max_connectionsof 100 shared with fmsg-webapi. - Longer term, the second option from finding 1: claim the rows and commit, deliver without a transaction open, then record outcomes. That removes the coupling between network time and DB connections.
Each outbound delivery holds one connection from the 32-connection sender pool for the whole exchange, so FMSG_MAX_CONCURRENT_SEND has no effect above 32. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
Pushed a README-only change (
|
Summary
High-impact security, correctness, performance, and maintainability improvements from a Go code review (strictly preserving
SPEC.mdwire conformance and existingdd.sqlschema):Security & Protocol Correctness
pkg/fmsg/fmsg.go,pkg/fmsg/deflate.go,cmd/fmsgd/host.go): Wrapzlib.Readerinio.LimitReader(zr, int64(expandedSize)+1), removeuint32truncation on written byte counts, checkzr.Close(), accumulate attachment sizes inuint64to preventuint32wrap bypassingMAX_SIZE/MAX_EXPANDED_SIZE, and useint64indeflate.go's compression ratio check.cmd/fmsgd/host.go,pkg/fmsg/prepare.go): Useio.ReadFullinto exact-sized buffers inhandleChallenge,ReadUInt8Slice,readHeaderpid, andchallenge; close connections on recovered panics inhandleConn; sendRejectCodeInvalidon duplicatetoand add-to attachment count mismatch; add cycle/depth bounds toisMessageRetrievable; deep-copyAddToFromandStoredWireinHeader.Clone().cmd/fmsgd/sender.go,cmd/fmsgd/store.go,cmd/fmsgd/host.go):msg_add_toupdates bybatch_id(preventing sibling batches from overwriting each other) and propagatetx.Execerrors.isLockedfor recipient entries matching the unit's table (msg_tovsmsg_add_to) so addresses in bothToandAddToaren't double-updated.localOutcomeintoattachAddToRecipientsand usestrings.EqualFoldfor local domain matching.h.Attachments[i].Filepathuntil all copies succeed, skippersistAttachmentPayloadsonskipData, deduplicate accepted local addresses before file copies and quota recording, and replace TOCTOUos.Stat+os.Createloops with atomicO_CREATE|O_EXCL.cmd/fmsgd/host.go,id.go,dns.go,sender.go): Add dial/IO deadlines anddefer conn2.Close()inchallenge; unwrap*tls.ConninabortConn; include attachment sizes in upload/download deadlines and set header write deadlines; use a dedicated pooledhttp.Clientwith timeout, non-200 rejection, and body draining inid.go; add resolver timeouts, reuse*dns.Client, and verify DNSSEC AD records directly indns.go; addSIGINT/SIGTERMgraceful shutdown and accept-error backoff inmain.Performance
*sql.DBpool (cmd/fmsgd/store.go,sender.go,indicators.go): Replace per-querysql.Open/defer db.Close()with a single shared connection pool.pkg/fmsg/prepare.go,pkg/message/store.go,cmd/fmsgd/sender.go,store.go,indicators.go): Exportfmsg.UnmarshalPreparedHeaderfor header-only reads, skip unused queries & double hashing inFinalizeBatch, track in-flightpendingTargetkeys inprocessPendingMessages, deferUnmarshalPreparedindeliverUnituntil pending rows are locked, compress directly to a temp file in destination dir inpreparePart, and poolzlib.Writerviasync.Poolinpkg/fmsg/deflate.go.cmd/fmsgd/indicators.go,pkg/fmsg/fmsg.go,cmd/fmsgd/host.go): GatesourceLimiterandipCachefull-map pruning at>= 1s, computeipCacheTTL after lookup, remove redundant 3rd DB query insubjectsOf, optimizeHeader.Encode()/Address.ToString()/GetCommonMediaTypeID/GetMessageHash, batch N+1 duplicate hash lookups, replacetime.Afterinselectloops with reusable timers, and deduplicatereadMediaType/addrEqualFold.Testing
uint32attachment size overflow, truncated challenge/slice reads, duplicateto/add-to attachment mismatch codes, cycle detection, atomicuniqueFilepath,id.go5xx handling,Header.Clone(),UnmarshalPreparedHeader,sourceLimiter/ipCachebehavior,deliverUnitTo ∩ AddTolocking, and DNSSEC validation.go vet ./...,go build ./..., andgo test -race -count=1 ./....