Repository navigation
Thread-safe connection lifecycle and TdLogger - #12
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
A production incident (2026-11-22): an AccessViolation while two threads connected to MySQL at once, with strace showing libmysqlclient loaded twice within a single run. The root cause is in fcl-db 3.2.2: the client library is loaded, initialised and released through unsynchronised process globals (TryInitialiseMysql increments RefCount before the function pointer table is filled and before mysql_library_init runs, while DoReleaseMysql at count zero calls mysql_library_end + dlclose under pointers other threads still use), and TDatabase.KeepConnection defaults to False, so every connection recreation cycles that load/unload machinery. Both entries into the broker's Connected transition (Connect/ Disconnect and the Connected property) now run under a process-wide critical section (Init/Done in initialization/finalization), and the created connection gets KeepConnection := True: the physical link survives the end of the last transaction, MaybeConnect never fires, and the library load/unload cycle is gone for the whole connection life. 46 tests pass (fpc -B 3.2.2 and lazbuild); a multithreaded smoke run of parallel Connect/query/Disconnect of two connectors (2 x 50 cycles, sqlite3) completes without crashes.
Every connector owns its TdLogger, but nothing keeps two connectors of one process from logging into the same file - that is two TFileStream handles writing one file in parallel. Log now writes under a process-wide critical section (Init/Done in initialization/ finalization) and seeks to the end of the file before every record: the file may have grown from the writes of another logger instance, and without repositioning the records would overwrite each other. OnLogging fires outside the lock, so a handler stays free to log itself instead of deadlocking on the non-reentrant section. The stream now opens with fmShareDenyNone in both modes (found by a multithreaded smoke test): without an explicit share mode TFileStream opens the file exclusively on Windows, and a second logger on the same file failed with EFOpenError right on activation; on Unix the share flags are ignored and nothing changes. SetFileName, SetActive and Destroy run under the same lock: they recreate or free FStream, and a parallel Log must not write into a freed stream. 46 tests pass (fpc -B 3.2.2 and lazbuild), including TestLoggerActivateAfterFileName; the smoke test logs 2 x 5000 records of two loggers into one file and gets exactly 10000 intact lines.
7d8f652 to
3ab4f4a
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7d8f652a7e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| EnterCriticalSection(ConnectionLock); | ||
| try | ||
| FCon.Connected := True; | ||
| finally | ||
| LeaveCriticalSection(ConnectionLock); |
There was a problem hiding this comment.
Serialize connector destruction with connection transitions
When a still-connected broker is destroyed while another thread connects a MySQL broker, its Destroy still calls FreeAndNil(FCon) without ConnectionLock. FPC's TSQLConnection.Destroy disconnects the connection, so driver teardown can still race the guarded Connect and trigger the same library-unload failure; guard this teardown with the same lock.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Valid catch — fixed in 001ce11. Verified against the FPC 3.2.2 sources: TSQLConnection.Destroy does Connected := False for a still-open connection, so destroying a connected broker ran the same unsynchronised client-library teardown as Disconnect, exactly the failure mode this branch fixes. TdSQLdbConnectionBroker.Destroy now frees FCon under ConnectionLock.
The multithreaded smoke run destroys connectors from two threads concurrently now (2 x 50 create/connect/query/disconnect/destroy cycles, no failures); 46 tests pass (fpc -B 3.2.2).
| FStream := TFileStream.Create(F, fmOpenReadWrite or fmShareDenyNone); | ||
| FStream.Seek(FStream.Size, soBeginning); | ||
| end | ||
| else | ||
| FStream := TFileStream.Create(F, fmCreate); | ||
| FStream := TFileStream.Create(F, fmCreate or fmShareDenyNone); |
There was a problem hiding this comment.
Preserve append integrity across processes
When two independent processes log to the same file on Windows, these share flags let both open it, but LoggerLock only coordinates threads in one process. Their separate Seek(0, soEnd) calls can observe the same end position and overwrite or interleave records; use cross-process append/locking or avoid enabling shared writes across processes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Acknowledged — resolved by documenting the boundary (55a3913) instead of adding locking, for three reasons:
- The share mode cannot be scoped to a process on Windows: whatever lets the second logger of the same process open the file also admits other processes, and refusing other processes would break the in-process case this PR exists to fix.
- On Unix there are no share modes at all, so the cross-process exposure predates this branch — nothing regressed there.
- Record locks (LockFileEx/fcntl) would add per-platform branches whose semantics (blocking on a wedged process, lock release on descriptor close) a single-machine test run cannot meaningfully exercise; Linux CI would compile them, but not verify them.
The contract now stated at LoggerLock: one log file per process (the date-suffixed names make that the natural setup), with all loggers of a process fully coordinated. If multi-process logging ever becomes a real requirement, cross-process locking can be a focused follow-up PR with CI-covered tests.
Codex review (PR #12): TSQLConnection.Destroy (fcl-db 3.2.2, sqldb.pp) sets Connected := False for a still-open connection, so freeing a connected broker from one thread ran the same unsynchronised client library teardown as Disconnect and could race a parallel transition of another broker of the process - the very failure mode this branch fixes. TdSQLdbConnectionBroker.Destroy now frees FCon under ConnectionLock. The multithreaded smoke run destroys connectors from both threads concurrently now; 46 tests pass (fpc -B 3.2.2).
Codex review (PR #12): LoggerLock coordinates the threads of one process only, and the share mode that several loggers of one process need on Windows admits any process, so two processes writing one log file could interleave records around their Seek/Write pairs. Resolved by documenting the boundary instead of adding locking: a share mode cannot be scoped to a process on Windows, Unix has no share modes at all (the file was shareable across processes before this branch too, so nothing regressed there), and record locks (LockFileEx/fcntl) would add per-platform code paths with semantics that a single-machine test cannot exercise. The comment on LoggerLock now states the contract: one log file per process, all loggers of a process fully coordinated; a follow-up PR can add cross-process locking with Linux CI coverage if that scenario ever matters.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 55a3913e8f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| EnterCriticalSection(ConnectionLock); | ||
| try | ||
| FCon.Connected := True; |
There was a problem hiding this comment.
Serialize implicit SQLdb connection opens
When a fresh connector follows the documented usage in README.md—without calling Connect, then starting a transaction or running its first query—SQLdb can open the connection through MaybeConnect without entering this lock. Two connectors can therefore still concurrently initialize the MySQL client before KeepConnection helps, leaving the reported crash reachable; serialize these implicit opens too or require and enforce an explicit Connect.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Valid catch — fixed in 21c8dd6. MaybeConnect in fcl-db 3.2.2 fires from exactly two places: TSQLTransaction.StartTransaction and statement Prepare (query Open/ExecSQL/Active := True). Every one of those paths in the broker now connects first through a new EnsureConnected helper: a cheap Connected check outside the lock, then a double-checked open inside ConnectionLock, so the implicit first open always passes the lock while statements and transaction starts stay parallel afterwards (with KeepConnection the connection stays up for its whole life, so only the first open pays). The query paths keep failing the old way when no database is assigned instead of dereferencing nil.
The smoke test now runs two connectors from two threads with no explicit Connect — one opens via its first query, the other via RunInTransaction — and destroys them still connected; no failures. 46 tests pass.
Codex re-review (PR #12): a connector that never calls Connect explicitly - the documented README usage - opens its connection through MaybeConnect from TSQLTransaction.StartTransaction or from statement Prepare (query Open/ExecSQL/Active := True), all outside ConnectionLock. Two fresh connectors could therefore still race the client library initialisation, and KeepConnection does not help there: it only prevents the close/reopen cycles after the first open. Every path that can MaybeConnect now connects first through the new EnsureConnected helper, which takes ConnectionLock only when the connection is actually down (double-checked), so the implicit open always passes the lock while statements and transaction starts stay parallel once the connection is up. The query paths keep their old failure mode without a database assigned instead of crashing on nil. The smoke test now opens two connectors from two threads without any explicit Connect (one via the first query, one via RunInTransaction) and destroys them connected; 46 tests pass (fpc -B 3.2.2).
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Context
A production incident on 2026-11-22 (a bot on FPC 3.2.2 + dOPF + fcl-db MySQL): a 9-hour outage with an AccessViolation (a wild control transfer, EIP in anonymous memory) while two threads connected to MySQL at the same time. strace showed libmysqlclient.so.21 loaded twice within a single run — the client library was being unloaded and loaded again on every connection recreation.
The cause is in fcl-db 3.2.2:
TryInitialiseMysqldoesInc(RefCount)BEFORE assigning the ~100 function pointers and BEFOREmysql_library_init, whileDoReleaseMysqlatRefCount=0callsmysql_library_end+dlcloseunder pointers other threads still use;MaybeConnect(fromTSQLTransaction.StartTransactionandTCustomSQLStatement.Prepare) reopens a dropped connection without synchronisation;TDatabase.KeepConnectiondefaults toFalse.Changes
brokers/dsqldbbroker.pas
TdSQLdbConnectionBroker.Create:FCon.KeepConnection := True— the connection no longer drops when the last transaction ends,MaybeConnect/auto-close never fire, and the client library unload/load cycle is gone.EnsureConnected: every path that canMaybeConnect(StartTransaction, queryOpen/Execute/Active := True) connects underConnectionLockfirst, so the implicit first open of a never-connected connector is serialised too.ConnectionLock(InitCriticalSection/DoneCriticalSectionininitialization/finalization);Connect,DisconnectandSetConnectedrun under it.core/dopf.pas
LoggerLock(Init/Donein the unitinitialization/finalization);Log,SetFileName,SetActiveandDestroyrun under it (the latter three recreate/freeFStream; a parallelLogmust not write into a freed stream). The lock is process-wide rather than per instance: each connector owns its ownTdLogger, but the file is shared.Logseeks to the end of the file (Seek(0, soEnd)) before writing: the file may have grown from another logger instance's writes; without repositioning, records would overwrite each other.OnLoggingfires outside the lock: a handler must stay free to log itself, otherwise it deadlocks on the non-reentrant section.OpenStreamopens the file withfmShareDenyNone(both modes): without an explicit share modeTFileStreamopens the file exclusively on Windows, and a second logger on the same file failed withEFOpenErrorright on activation (found by a multithreaded smoke test). On Unix the share flags are ignored and nothing changes.Tests
46/46 pass on both toolchains:
fpc -B(FPC 3.2.2, as in production) andlazbuild -B(the dopfrt package + the console runner), includingTestLoggerActivateAfterFileNameand 14 transaction tests on sqlite3. An extra throwaway multithreaded smoke test: 2 threads x 5000 records of twoTdLoggers into one file = exactly 10000 intact lines; 2 threads x 50 Connect/query/Disconnect cycles of two connectors in parallel — no crashes.Global state review
No unit-level
var/threadvar/caches exist incore/dopf.pas,brokers/dsqldbbroker.pasor the units they call from Open/Execute (dutils,dsqlbuilder,dclasses) — all state lives in instance fields.Residual risks
MaybeConnect(brokerStartTransaction, queryOpen/Execute/Active := True) connects first throughEnsureConnected, which double-checks and opens underConnectionLock. What stays outside the lock is fcl-db's internal reconnect of a connection that died mid-life (a network/server failure noticed between our check and the statement): withKeepConnection=Truethat is a rare path, and closing it would mean serialising every statement.TSQLQuery.Open/ExecSQL(Prepare->MaybeConnect) — the same rare path inside fcl-db; wrapping it would effectively serialise all SQL and is not recommended.ConnectionLockandLoggerLockare never held nested.