Skip to content

Thread-safe connection lifecycle and TdLogger - #12

Merged
Al-Muhandis merged 5 commits into
mainfrom
threadsafe-connection-lifecycle
Nov 22, 2026
Merged

Al-Muhandis merged 5 commits into
mainfrom
threadsafe-connection-lifecycle

Conversation

@Al-Muhandis

@Al-Muhandis Al-Muhandis commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

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: TryInitialiseMysql does Inc(RefCount) BEFORE assigning the ~100 function pointers and BEFORE mysql_library_init, while DoReleaseMysql at RefCount=0 calls mysql_library_end + dlclose under pointers other threads still use; MaybeConnect (from TSQLTransaction.StartTransaction and TCustomSQLStatement.Prepare) reopens a dropped connection without synchronisation; TDatabase.KeepConnection defaults to False.

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 can MaybeConnect (StartTransaction, query Open/Execute/Active := True) connects under ConnectionLock first, so the implicit first open of a never-connected connector is serialised too.
  • A process-wide unit critical section ConnectionLock (InitCriticalSection/DoneCriticalSection in initialization/finalization); Connect, Disconnect and SetConnected run under it.

core/dopf.pas

  • A process-wide critical section LoggerLock (Init/Done in the unit initialization/finalization); Log, SetFileName, SetActive and Destroy run under it (the latter three recreate/free FStream; a parallel Log must not write into a freed stream). The lock is process-wide rather than per instance: each connector owns its own TdLogger, but the file is shared.
  • Log seeks 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.
  • OnLogging fires outside the lock: a handler must stay free to log itself, otherwise it deadlocks on the non-reentrant section.
  • OpenStream opens the file with fmShareDenyNone (both modes): 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 (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) and lazbuild -B (the dopfrt package + the console runner), including TestLoggerActivateAfterFileName and 14 transaction tests on sqlite3. An extra throwaway multithreaded smoke test: 2 threads x 5000 records of two TdLoggers 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 in core/dopf.pas, brokers/dsqldbbroker.pas or the units they call from Open/Execute (dutils, dsqlbuilder, dclasses) — all state lives in instance fields.

Residual risks

  • Implicit opens are serialised: every path that can MaybeConnect (broker StartTransaction, query Open/Execute/Active := True) connects first through EnsureConnected, which double-checks and opens under ConnectionLock. 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): with KeepConnection=True that 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.
  • No deadlocks are possible: ConnectionLock and LoggerLock are never held nested.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T19:51:51.330905Z 21c8dd6 Manual request
ℹ️ 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" or "@codex security review".

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.
@Al-Muhandis
Al-Muhandis force-pushed the threadsafe-connection-lifecycle branch from 7d8f652 to 3ab4f4a Compare November 22, 2026 19:17

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread brokers/dsqldbbroker.pas
Comment on lines +195 to +199
EnterCriticalSection(ConnectionLock);
try
FCon.Connected := True;
finally
LeaveCriticalSection(ConnectionLock);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread core/dopf.pas
Comment on lines +532 to +536
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acknowledged — resolved by documenting the boundary (55a3913) instead of adding locking, for three reasons:

  1. 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.
  2. On Unix there are no share modes at all, so the cross-process exposure predates this branch — nothing regressed there.
  3. 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.

@Al-Muhandis Al-Muhandis changed the title Потокобезопасность жизненного цикла соединения и TdLogger Thread-safe connection lifecycle and TdLogger Nov 22, 2026
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.
@Al-Muhandis

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread brokers/dsqldbbroker.pas
Comment on lines +204 to +206
EnterCriticalSection(ConnectionLock);
try
FCon.Connected := True;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).
@Al-Muhandis

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 21c8dd6fbd

ℹ️ 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".

@Al-Muhandis
Al-Muhandis merged commit 0e2e0bb into main Nov 22, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant