Repository navigation
Release candidate v26.09.23: async handler offload, auth.* over MCP, and the security work to ship them - #144
Merged
Merged
Conversation
…self Landing the supporting work separately so each part is reviewable on its own and none of it depends on the offload being finished. 1. ports/crow - a vcpkg overlay port carrying one patch. Crow already supports deferred completion: while a response is incomplete the read loop stops and records need_to_start_read_after_complete_, so no second request can land on that connection. What it does not offer is a way to keep the connection ALIVE across that window. prepare_buffers() starts by clearing complete_request_handler_ and is_alive_helper_. From the original io callback that is safe, because do_read's lambda still holds `self` on the stack. From a completion posted after that callback returned, those two lambdas are the only owners - so clearing them destroys `this` and every line after is a use-after-free. That is precisely where the prototype crashed. The patch adds a public shared_ptr<void> on crow::response, set alongside the existing handler and cleared alongside it, which a handler can capture to hold the connection open. Verified by experiment: the offload experiment that crashed reliably now answers 40/40 probes with none blocked and the server still alive. Synchronous handlers never touch it, and it is reset on the same lines as the references it sits with, so it adds no cycle of its own. 2. HandlerPool - bounded, with a real shutdown. The prototype had an unbounded queue and no shutdown ordering. An unbounded queue turns a slow backend into unbounded memory and unbounded latency, and eventually serves a client that stopped waiting long ago - so submit() refuses when full and the caller answers 503. Shutdown DRAINS rather than drops: every queued job owns a connection waiting for a response. 3. SpanScope::Activation - re-activate a span on another thread. OpenTelemetry's active-span stack is thread-local, which is what lets the inner pipeline parent its spans without threading a parameter through DatabaseManager, SQLTemplateProcessor and QueryExecutor. Work moved to another thread therefore starts with whatever that thread last had on top, and its inner spans would re-parent or become roots. Implemented in both twins; a no-op when tracing is compiled out. 4. RequestContextScope::clearIf - clear only what you own. finish() runs on the io thread, which once handlers can be offloaded may have picked up a different request by the time the completion posts back. An unconditional clear strips the newcomer of its context: no request id on its audit line, no correlation on its log lines, and no error either way. Not yet wired up: nothing calls the pool, so behaviour is unchanged. The offload itself, and its measurement, come next. 752 unit tests.
Wires up the pieces from the previous commit. Handlers now run on a bounded worker pool and the response is completed back on the connection's own io_service, holding the connection open with the keepalive handle the crow overlay port adds. Measured, one ~6.5s query with 40 concurrent probes, a single io thread: offload OFF : 40/40 probes blocked, 0/40 reported the stall, worst 5.04s offload ON : 0/40 probes blocked, 40/40 reported the stall, worst 0.005s That is the whole of #120: the probe could not report a stall because the stall was blocking the probe. An earlier run of this measurement was WRONG and is worth recording. It reported "0/40 blocked" with offload on and I nearly wrote it up as a success - but 0/40 also reported the stall, which made no sense. The server had never started: /slow returned 000 in 0.2ms and the config file was missing, so all forty "probes" were instant failures. The script now sanity-checks that /slow really is slow and counts failed requests separately, and every number above comes from a run where /slow took 6.5s and nothing failed. What crosses the thread boundary, and why each is needed: - the keepalive handle, or prepare_buffers() destroys the connection mid-function once the io callback has returned; - RequestContextScope::activate on the worker and clearIf on the way out, so the audit line keeps its request id and a job that raced us is not stripped of its context; - SpanScope::activateOnThisThread, because OpenTelemetry's active-span stack is thread-local and the inner pipeline relies on it for parenting. The tracing and audit integration tests now exercise that boundary on every request rather than testing it directly - inner spans, trace correlation and the audit log are all green with the offload on by default, which is the evidence that the three rebindings work. Saturation sheds rather than queues: a full pool answers 503 with Retry-After. Silently queueing would eventually serve a client that stopped waiting. FLAPI_DISABLE_HANDLER_OFFLOAD=1 restores the inline path, for a deployment that hits something this did not anticipate. 757 unit tests, 372 standalone integration tests. Note for review: the crow overlay port cannot be exercised locally - vcpkg has no network in this environment - so the installed headers were patched by hand with the port's own patch to build and measure. CI is the first place the port itself runs.
F1 - the handler pool outlived the Crow app. handlerPool was declared BEFORE app, so ~APIServer destroyed the io contexts and connections before joining the workers, and stop() never touched the pool at all. A worker still mid-query at SIGTERM would finish, post to a destroyed io_service, then drop a keepalive holding a connection whose socket belonged to it. The pool's "drain, don't drop" promise was vacuous after app.stop(): no posted completion can run. shutdown() now happens BEFORE app.stop(), and the member is declared after app so destruction order is safe regardless. F5 - completion was a code-path property, not a structural one. The job caught std::exception only. Anything else escaped to HandlerPool::run's catch(...), which logged and dropped it - so no completion was posted, and the connection was left held only by its own self-references with the read loop paused and the deadline timer cancelled. finish() never ran, the in-flight slot never cleared, and readiness reported 503 for the life of the process. An RAII Completer now posts something on every exit path, so "complete exactly once" holds by type rather than by remembering. F11 - the io thread kept claiming a request after handing it away. t_current stayed set until the posted completion ran. Crow logs "Request:" for the NEXT connection on that thread before its before_handle runs, so those lines carried the offloaded request's id and trace id - mis-correlating exactly the logs this release advertises. Cleared right after a successful submit. F6 - out-of-order OTel scope detach. SpanScope::Impl pushed a context scope on the io thread and popped it in finish(). While handlers ran inline that was strictly nested. With the offload, two requests on one io thread can finish in the other order, and a non-LIFO Detach fails: the token stays on the stack, later requests without a traceparent parent to an ended span, and each mismatched pair leaks a shared_ptr. The scope is now optional, and the offload path releases it immediately after submit while it is still innermost; the worker re-activates on its own thread. Inline paths are untouched. Also: my own offload tests did not discriminate. The review found three of the four tests added with #137 would pass against the defect they claimed to pin. test_handler_offload.py said so in its own docstring - it used the shipped thread count, and on a many-core machine the condition never arises, so the pre-offload server passed it. FLAPI_IO_THREADS forces the minimum (one accept + one io thread) so the condition actually occurs, and a new test asserts requests ARE blocked with FLAPI_DISABLE_HANDLER_OFFLOAD=1 - so the others now demonstrably measure something. 757 unit tests, 377 standalone integration tests.
CI caught what I could not build locally: `include/crow/http_connection.h:195: patch does not apply`. Two mistakes, and the second is the one that mattered. 1. The patch was generated against the wrong source. I diffed the headers installed in vcpkg_installed/, which are crow 1.2.0. The port I copied from upstream fetches v1.3.0, where `self` is captured from an outer scope rather than re-acquired inside the `if (!res.completed_)` block - so my context did not match. The lifetime analysis holds in 1.3.0 unchanged; only the patch context differed. 2. The port would have SILENTLY UPGRADED crow. I copied the upstream port wholesale, which declares 1.3.0. This project builds 1.2.0 - vcpkg.spdx.json in the installed tree says so. Adding a three-line patch would have carried a dependency minor-version bump with it, in a PR about request handling, with nobody asking for it and nothing testing the difference. The port is now pinned to the 1.2.0 tarball the project already builds, with the SHA512 of the tarball in the vcpkg download cache, so the patch is the only change. Also dropped remove-cpm.patch, which came with the copied port: it targets 1.3.0's CMakeLists, and 1.2.0 has no CPM reference at all, so applying it fails. Verified against a pristine copy of the 1.2.0 source rather than against my own tree: the patch applies cleanly, both files. This is exactly the caveat I flagged on the PR - the overlay port cannot be exercised locally because vcpkg has no network here, so CI is the first place it runs. It was right to flag it and wrong to assume it would hold.
…build (F9, F10, F13)
F9 - the incremental watermark pointed two refreshes back.
fetchSnapshotInfo runs BEFORE the refresh writes anything, so the newest
existing snapshot is already the last completed refresh. previousSnapshot*
carried index 1 instead - one further back - while CONFIG_REFERENCE
documented previousSnapshotTimestamp as "Last refresh timestamp" and its
example used it as
WHERE updated_at > TIMESTAMP '{{cache.previousSnapshotTimestamp}}'
So an append template re-read every row the previous refresh had already
appended, silently, and a table's second-ever refresh had no previous at
all - the incremental section did not render and it reloaded everything.
Merge mode masked it: duplicates collapse on the primary key.
BEHAVIOUR CHANGE: incremental refreshes now load a narrower, correct
window.
A second docs defect found while checking it: {{cache.currentSnapshotTimestamp}}
is documented and has NEVER existed - the implemented name is
{{cache.snapshotTimestamp}}. A template using the documented name renders
an empty string, which inside WHERE ... > TIMESTAMP '' is a SQL error.
Same class as the config keys that were documented and never read.
F10 - short credentials were returned verbatim by _dryRun.
The scrub skipped values under four bytes, so a three-character password or
PIN interpolated through conn.* came back to any caller, and MCP is
unauthenticated by default.
Redacting them regardless is not the fix either: scrubbing works by value,
because the key is gone by the time the SQL is rendered, and a one-byte
secret matches ordinary text. Measured - redacting "a" rewrote the middle
of an unrelated file path and broke the preview.
So the preview is WITHHELD when a connection holds a credential too short
to replace safely, with a message saying why. Neither leaking nor mangling.
Tested both ways: a short secret withholds, a normal connection still gets
its preview.
F13 - the tracing-off tree was stale.
Rebuilt from scratch against all the merged work; flapi-lib compiles and
links clean. Correcting the finding on one point: both binary resolvers
(conftest.py:107 and otel_helpers.py:30) default to RELEASE, not debug, so
the integration runs did exercise the right binary.
My own watermark test failed on the F9 change, correctly: it asserted the old
index-1 contract. Restructured so the scenario still discriminates - table A
moves twice, then B, so the catalog's newest belongs to B while A's own is
older - and it now also asserts the watermark is A's LAST refresh rather than
the one before it.
755 unit tests, 378 standalone integration tests.
The re-review of the release candidate found eight blockers, five of them
repeats of the first review's own failure mode: the instance was fixed and
the siblings were left. Each fix here is made at the point where the
siblings cannot diverge again.
MCP never injected the authenticated identity (F3)
MCPToolHandler stripped the caller's `__auth_*` and then never put the
real principal back, so `auth.*` was unconditionally EMPTY over MCP even
for an authenticated caller. Only REST injected it. The documented
multi-tenant template
{{#auth.username}}WHERE tenant = '{{ auth.username }}'{{/auth.username}}
therefore rendered NO filter over MCP and returned every tenant's rows to
any authenticated caller; the unconditional form rendered `tenant = ''`
and returned none. Both silent. The identity was already in
tool_request.context - nothing read it.
A second, stale copy of the slug codec (F6)
Only cli/src/lib/url.ts was rewritten for the '~1'/'~0' codec.
cli/shared/src/lib/url.ts kept the old '-slash-' one, and that is the copy
bundled into @flapi/shared, imported by the shared apiClient and by the
VSCode extension - which therefore encoded '/customers/' as
'customers-slash' against a server expecting '-customers-', 404ing every
config call. The unit test imported the updated duplicate, so it could not
see the disagreement. There is now one implementation; the CLI re-exports
it and the test runs against the package that actually ships.
Two more config tools reporting fabricated success (F5)
flapi_update_template was made to refuse. Its two siblings 40 lines away,
flapi_expand_template and flapi_test_template, still answered with a
hardcoded `SELECT * FROM data WHERE 1=1` and "Template expanded
successfully" / "Template test passed" - to unauthenticated callers, since
both are auth_required=false. "Is this implemented" now lives in the
registration, not in the handler bodies: an unimplemented tool is never
advertised by tools/list and is refused centrally by executeTool.
Offload dereferenced null on the heartbeat path (F1)
requestForEndpoint() synthesises a bare crow::request with no io_service
and no middleware context and calls handle_full directly. The new offload
path dereferenced both. It now runs inline, which is also correct - there
is no connection to keep responsive.
Count-based retention expired snapshots catalog-wide (F2)
keep-last-snapshots is per endpoint, but every cached endpoint shares one
DuckLake catalog and the expiry listed snapshots catalog-wide. One
endpoint's retention destroyed every other endpoint's history and
watermark. The per-table predicate already existed in fetchSnapshotInfo -
the same defect fixed in the same commit - so it is now one shared
definition used by both. Retention additionally expires only snapshots
that touched nothing else: keeping too much history is recoverable,
deleting another endpoint's data is not.
Tests
Each is red without its fix, verified by reverting and rebuilding, and
drives the product rather than a reimplementation. The retention test uses
TWO tables - the existing one used a single table and so could not see the
defect. The MCP tool tests assert the property ("no tool fabricates")
across all three tools rather than naming the one that was broken.
762 unit / 11+18 integration green.
Co-Authored-By: Claude Opus 5 <[email protected]>
…safe (F4, F7)
Dry-run scrubbing covered one of three sources (F4)
A template can interpolate `conn.*`, `env.*` and `params.*`. Only conn.*
was scrubbed, so an unauthenticated `_dryRun` (MCP is unauthenticated by
default) still recovered:
- a whitelisted environment secret, the documented
`{{{ env.API_KEY }}}` pattern; and
- a credential-valued request `default:`, which is copied into params and
echoed back in the payload's own `parameters` object even when the SQL
itself was clean.
MCPDryRun::Secrets now enumerates every source in one place and applies the
same withhold-rather-than-mangle rule to all of them; `parameters` is
redacted by key, which is exact.
Found while writing the test: stripping `_dryRun` left a NULL wvalue, so
applyDefaultArguments called has() on a non-container and a dry run of any
endpoint declaring a `default:` failed with "value is not a container".
Fixed in both places.
SIGTERM ran the whole shutdown inside the signal handler (F7)
APIServer::stop() - which now joins every pool worker under a mutex - was
called directly from the POSIX handler. A signal is delivered on whichever
thread is running, so SIGTERM landing on a pool worker meant that worker
joining itself. The handler now does nothing but set a flag and write one
byte to a self-pipe; a supervisor thread performs the shutdown. Handlers
also get SA_RESTART: without it a signal made every blocking syscall in
every thread return EINTR at once, which aborted the process with
"corrupted double-linked list" rather than shutting it down.
Chasing that turned up a worse, unreported bug. Crow installs its own asio
signal_set for SIGINT/SIGTERM, and asio REPLACES the sigaction main()
installed - so flapi's handler never ran, the pool was never drained, and
~APIServer joined a worker during STATIC DESTRUCTION. That worker was still
inside a query and reached QueryExecutor's function-local statics after
they had been destroyed:
#0 flapi::unregisterActiveExecutor(std::thread::id)
#1 flapi::QueryExecutor::execute(...)
#8 flapi::HandlerPool::run()
-- main: exit() -> ~APIServer -> ~HandlerPool -> join()
i.e. SIGTERM during an in-flight query could segfault, from a plain
`kill -TERM`. Two independent fixes: crow no longer installs the handlers
(flapi handles these signals itself), and main drains the pool before
returning rather than leaving it to a static destructor.
HandlerPool::shutdown also takes a drain budget, so one slow queued job
cannot hold shutdown open until the platform SIGKILLs the container.
Tests
The dry-run tests are red without their fix, verified by reverting and
rebuilding, and name the SOURCE rather than the property that was broken.
The SIGTERM tests are honest about their limits. Every other fixture in
test_handler_offload.py stops the server with SIGKILL, so this path had
never been exercised at all; these drive real SIGTERM, including delivery
to every thread via tgkill(2). The segfault above is a race - reproduced
from a core dump, not reproducible on demand - so these are a regression
net, not a red/green proof of that specific crash. The assertion is
`exit code == 0`: the first version asserted only "it exited" and passed on
the SIGSEGV.
762 unit green; offload, dry-run-secrets, auth-context and MCP config-tool
integration suites green.
Co-Authored-By: Claude Opus 5 <[email protected]>
…ime (F8)
previousSnapshotTimestamp was ducklake_snapshots.snapshot_time - the instant
the previous refresh COMMITTED. That refresh read the source at some earlier
instant T_read. A source row written at T with
T_read < T <= T_commit
was not read by refresh N, and refresh N+1's
`WHERE updated_at > TIMESTAMP '<T_commit>'` excludes it as well. On a
continuously-written source every refresh permanently drops the rows written
during its own execution and reports success - invisible under append AND
merge, because there is nothing there to duplicate or collapse.
The previous fix in this area traded silent duplication (harmless under merge,
visible under append) for silent loss. Loss is the worse trade.
With a `cursor:` configured the watermark is now `max(<cursor column>)` over
the rows actually cached. Rows above it are exactly the rows not yet loaded,
with no window in which a write can fall through. A row exactly at the
boundary may be re-read: idempotent under merge, a bounded and visible
duplicate under append. Without a cursor there is no incremental filter to
drive, so the snapshot timestamp remains the fallback - as it does when the
cache table does not exist yet or is empty.
The test writes a row into the window the previous refresh was running in and
asserts it is above the watermark, and that an already-cached row is not - so
it cannot pass by simply reloading everything. Red without the fix, verified
by reverting and rebuilding.
CONFIG_REFERENCE and the caching component doc now say where the value comes
from and why, and note that it is rendered raw so a non-timestamp cursor needs
quoting appropriate to its type.
763 unit tests green.
Co-Authored-By: Claude Opus 5 <[email protected]>
The target's readiness probe was a python3 -c one-liner containing an indented for/try block, which is a SyntaxError - so every invocation died before pytest, killed the server, and exited 1. `make integration-test-ci` has therefore never run a single integration test. Verified identical on the pre-fix baseline, so this is not a regression from the blocker work; CI calls pytest directly and was unaffected. Replaced with a shell loop over curl. Co-Authored-By: Claude Opus 5 <[email protected]>
…w streams
The handler offload runs a handler on a pool thread against a LOCAL
crow::response and posts the result back to the connection's io thread.
Completer::take carried code, body and headers - and nothing else.
crow::response has three more data members, and dropping `compressed` silently
corrupted every Arrow IPC response. The Arrow path sets `compressed = false`
(the payload carries its own LZ4/ZSTD framing) together with an explicit
Content-Length. The flag was lost on the hop, so Crow gzipped the body while
the length header described the uncompressed size, and every client read a
truncated stream:
IncompleteRead(826858 bytes read, 1851846 more expected)
15 of 18 tests in test_arrow_streaming.py fail on the offload branch and pass
on main. Neither the first review nor the re-review caught it, and it was not
among the eight blockers - it surfaced only from running the whole integration
suite the way CI does.
`skip_body` (HEAD responses) and `manual_length_header` were dropped the same
way and are now carried too.
scripts/check_crow_response_fields.py fails the build if crow::response grows a
field the offload does not carry, or if Completer stops carrying one. A future
crow version would otherwise reintroduce this exactly: compiles cleanly, fails
only at runtime, only on whichever feature uses the new field. Wired into the
"Check codebase invariants" CI step.
The guard refuses to pass vacuously - its first version parsed zero fields and
reported OK. Both failure branches are verified by hand: dropping
`compressed = from.compressed` and removing a field from CARRIED each make it
exit 1.
Arrow: 18 passed, 11 skipped - identical to main.
Co-Authored-By: Claude Opus 5 <[email protected]>
… tests
A crew re-review of the eight blocker fixes returned REQUEST_CHANGES: the diff
fixed its named instances and missed siblings again, in the same pattern it
exists to break. This is the first half of that response; every finding here
was verified in the tree.
Retention was only half fixed (F2-AGE, SCHEMA-ID)
`max-snapshot-age` and manual GC still called
`ducklake_expire_snapshots(cat, older_than => ...)`, which has NO per-table
form - it acts on the whole catalog, and every cached endpoint shares one.
Either still destroyed every other endpoint's history and incremental
watermark. Manual GC was worse: a hardcoded one-day cutoff that ignored the
configured policy entirely. Both now resolve explicit per-table snapshot ids
through the same path the count-based branch uses.
The table id was resolved by `WHERE table_name = 'x' LIMIT 1` with no schema
predicate. Verified on DuckDB 1.5.5: a catalog holding s1.orders and
s2.orders returns two rows differing only in schema_id, and
ducklake_table_info() exposes no schema NAME to tell them apart. Harmless
while it fed a read-only watermark; it now feeds expiry, so an ambiguous
lookup resolves to nothing and retention is disabled with a warning rather
than risking another table's data.
The cursor watermark fell back to a commit timestamp (F8-FALLBACK)
The two values do not share a type. With `cursor: {type: int}` over an empty
cache table the fallback rendered `WHERE seq > 2026-09-23 10:00:00` - a
binder error; with a timestamp cursor it rendered `> '<table create time>'`
and dropped every older source row forever, which is the silent loss F8 was
raised to remove. It is now erased, so the template takes its full-load
branch. The watermark and the cursor column are escaped and quoted.
Four more config tools fabricated success (F5-SIB)
flapi_refresh_cache returned "Cache refresh has been scheduled" - this
adapter holds no CacheManager reference at all. flapi_run_cache_gc and
flapi_refresh_schema the same. flapi_get_cache_audit INVENTED audit rows
under the comment "Add sample audit entry": an agent asking for an audit log
received manufactured records, which is the worst thing a stub can return.
All four are now registered unimplemented.
Tests that could not fail
- The "property-based" no-fabrication test was a hardcoded three-name list.
That is exactly why the four above survived. It now enumerates tools/list
and judges what comes back, plus an observable-effect spot check on a
mutating tool.
- test_mcp_config_tools.py asserted only `result is not None` for the
template tools, so it passed against the fabricated SQL for as long as it
shipped.
- test_ducklake_scheduler.py used the pre-codec slug `customers` (the slug
is `-customers-`) AND `/customers/`, which is the UNCACHED endpoint in the
test config, with every assertion behind `if status_code == 200`. Three
independent reasons it asserted nothing. The slug is now built with the
codec itself, it targets /customers_cached/, and the guards are gone.
- A tavern case asserted `endpoints/customers%2F` resolved. It never passed:
the routes are `<string>` (one path segment) and Crow percent-decodes
before matching. Rather than add a second reachable name - the ambiguity
#123 removed - the path fallback in identifierToPath is gone and the case
asserts the 404.
- cache_manager_test.cpp REQUIRED an `older_than` call, pinning the bug.
New tests: age-based retention and manual GC leave another endpoint alone; a
snapshot shared by two tables is never expired (one transaction writing both,
verified to produce `{inlined_insert=[2, 3]}`); two schemas with the same table
name expire nothing; an empty cache table with an int cursor falls back to a
full load rather than to a timestamp.
768 unit green; mcp_config_tools 42, ducklake_scheduler 7, config_tool_auth 12.
Co-Authored-By: Claude Opus 5 <[email protected]>
…gnal safety
Second half of the crew re-review response. F1 turned out never to have been
fixed at all.
F1 was fixed in the wrong place, and my own new test found it
The offload guard sent synthesised requests INLINE to handleDynamicRequest -
which does `app.get_context<AuthMiddleware>(req)` four hundred lines away,
the same null dereference. So the crash simply moved:
#0 flapi::APIServer::handleDynamicRequest(...)
#4 flapi::APIServer::requestForEndpoint(...)
#5 flapi::HeartbeatWorker::performHeartbeat(...)
Every deployment with a scheduled cache was still crashing, and the fix had
shipped with no test at all. The new heartbeat test - a cached endpoint on a
1s schedule, asserting the process still answers - is red against the
unguarded version.
The identity was missing on a second MCP surface (F3-RES)
resources/read authenticates and applies per-resource RBAC, then passed its
bound URI-template params straight to executeQuery: no `__auth_*` strip, no
injection. `auth.*` was unconditionally empty, so the documented
`{{#auth.username}}WHERE tenant = ...{{/auth.username}}` filter rendered
NOTHING and returned every tenant's rows to any authenticated caller.
Identical to the tools/call defect, one method over - because that fix was
made inline in prepareParameters instead of in a helper both surfaces call.
Now applyMcpAuthContext, called from both. prompts/get was checked: it
renders no SQL template and needs nothing.
auth.email went the same way: REST injects it, CONFIG_REFERENCE documents it,
and MCPSession::AuthContext had no field for it, so a filter on it rendered
over REST and rendered nothing over MCP. Added and populated from the OIDC
claims and the bearer token.
Secrets leaked through the error path (ERR-LEAK)
The dry-run preview was scrubbed; the error was not. DuckDB quotes the
failing statement in its message, and that message went straight back to an
unauthenticated caller. The secret set is now collected for every path and
the error message scrubbed with it. Env values also get length-based
widening (>= 24 chars) beyond the name heuristic, which cannot recognise
PAYMENT_VALUE or SERVICE_ACCOUNT_JSON; the heuristic stays the gate for
request defaults, where redacting `default: "100"` would ruin the preview.
Signal handling and shutdown (STOP-RACE, SIG-WINDOW)
- HandlerPool::shutdown() returned early on a second call, BEFORE the join
loop, so the second caller believed a pool drained that had joined
nothing - the path the original SIGSEGV came from. It now serialises and
waits. APIServer::stop() likewise.
- The supervisor started only after config load and DB init, a window of
seconds in which the default disposition was already gone, so SIGTERM did
nothing. It now starts with the handlers, tolerates a not-yet-built
server, and a signal during startup stops the process rather than letting
it come up and serve.
- pipe2(O_CLOEXEC); O_NONBLOCK on the WRITE end only. Setting it on both
made read() return EAGAIN, the supervisor exit at startup, and SIGTERM do
nothing at all - "strictly worse than what it replaced", exactly as the
review warned. The termination tests caught it.
- If the pipe cannot be created the handlers are not installed at all, so
the signals keep their default disposition rather than becoming inert.
- api_server is read by the supervisor and written by main, so both go
through a mutex.
Tests
- The tgkill test skips off x86_64/aarch64 Linux instead of reporting a
fabricated hang - flapi ships ARM64 binaries.
- The supervisor test no longer claims evidence it does not produce; it
asserts the clean exit status and says so.
- The watermark section no longer asserts arithmetic against SQL the test
wrote; it states the relation between the watermark and the data.
- cli `pretest` builds @flapi/shared, so the codec test can no longer
validate a stale dist - verified by breaking the source and watching it go
red. apiClient's six hand-built endpoint URLs now go through
buildEndpointUrl, which encodes.
Docs: cache.snapshotTimestamp is NOT previousSnapshotTimestamp any more, and
the `>` comparison's residual boundary-row window is stated rather than
claimed away.
768 unit green; offload 11, dry-run-secrets 15, auth-context 13, cli 46.
Co-Authored-By: Claude Opus 5 <[email protected]>
buildExpireSql ran expirableSnapshotIds twice when nothing was expirable - once for the list, once to decide whether to log "all shared" - which meant a second full snapshot scan on the common early-life path where a policy has nothing to do yet. The exclusivity test is now SELECTed as a column rather than filtered on, so one query returns both what may be expired and how many eligible snapshots are shared with another table. The log line says which of "nothing old enough" and "nothing expirable" happened; those look identical from the outside, and the second means a configured policy silently never fires. The mock adapter had to learn the column: without it every row read as shared, so the retention tests would have passed on an empty expiry. Two new sections cover the shared path and the unshared-beside-shared path, which the real-catalog tests exercise end to end but could not express selectively. 768 unit green. Co-Authored-By: Claude Opus 5 <[email protected]>
User-facing only: what changes for someone running flAPI, what they have to do about it, and the measurements behind the claims. The offload numbers, the auth.* behaviour change on MCP templates, the retention and watermark data-loss fixes, the credential disclosure paths, the config tools that stopped lying, and the slug codec's CLI/extension coupling. Co-Authored-By: Claude Opus 5 <[email protected]>
A template guarded on {{#cache.previousSnapshotTimestamp}} or
{{#cache.previousSnapshotId}} now renders its full-load branch when a cursor
is configured but max(cursor) cannot be read - a new or still-empty cache
table. That is deliberate (the alternative was a type-incoherent timestamp
fallback that silently dropped rows), but it was only stated for the
timestamp.
Co-Authored-By: Claude Opus 5 <[email protected]>
…ocation
The SIGTERM-window fix started the supervisor thread as soon as the handlers
were installed, so that a signal during config load or DB init is acted on.
But main() returns from a dozen places - `flapi pack`, `unpack`, `info`, every
argument-parsing error - and a joinable std::thread whose destructor runs calls
std::terminate. So every short-lived invocation of the binary aborted.
36 integration tests went red on it: test_self_packaging, test_env_overrides,
test_config_error_exit, test_vfs_e2e, test_password_hashing,
test_security_warnings, test_mcp_description_hygiene - everything that runs
flapi as a subprocess and reads its exit status. All 43 pass again.
The supervisor is now owned by an RAII guard at main() scope, so every return
path closes the write end and joins, including the ones that never built a
server.
Also rewrites the MCP workflow tests, which were the last group written as
try: assert call_tool(<a tool that does nothing>) is not None
except Exception as e: assert "cache" in str(e).lower() or ...
a shape that passes whether the tool fabricates a result, works, or raises for
any reason at all. They now assert that the unimplemented step refuses and
names the REST route that does the work, while the implemented steps around it
still succeed. Two further problems they had been hiding:
- the cache workflows addressed /customers/, which is the UNCACHED endpoint
in the test configuration, so they only ever exercised "Cache not enabled
for this endpoint";
- test_concurrent_schema_refreshes called a stub three times and asserted
three non-None results, which a constant satisfies perfectly. It now reads
the real schema and asserts the three answers agree.
Co-Authored-By: Claude Opus 5 <[email protected]>
…-3 findings
A third crew review found that eleven config tools fabricated results, not
seven - and that marking them unimplemented was the wrong fix, because every
one of them had a working REST handler this adapter was constructing and then
discarding.
Config tools now delegate (was: refuse)
flapi_get_environment returned an empty list, flapi_get_filesystem an empty
tree, flapi_get_schema `"tables": null`, flapi_get_project_config a
hardcoded version "1.0.0", and flapi_get_cache_status three fields of static
YAML while its description promised "snapshot history and refresh
timestamps". None was in the unimplemented registry, so tools/list
advertised all five as working.
All eleven now call the handler the corresponding REST route calls, so the
two surfaces cannot disagree and the handlers' existing coverage applies to
both. The unimplemented registry stays as the structural guard; it is simply
empty. Descriptions that promised more than the body returned are corrected.
Secrets on every surface, not just MCP tools/call (round 2 left two siblings)
resources/read and BOTH REST catch blocks returned e.what() verbatim, and
DuckDB quotes the failing statement - the rendered template. The MCP fix was
justified by "MCP is unauthenticated by default"; REST auth is per-endpoint
and equally optional. The secret set moved to template_secrets.{hpp,cpp} so
all three call one collector and one scrub, rather than the MCP header being
included by RequestHandler.
The error path no longer reuses the dry-run "withheld" wording, which
described a preview and let any caller suppress every diagnostic for a call
by passing a short value under a name like `token`.
Retention
- `keep-last-snapshots` was applied to the already-age-filtered set, so
`keep-last-snapshots: 3` with `max-snapshot-age: 7d` - the pair the
examples ship - kept "3 stale plus everything newer than 7d". Both
predicates are now selected and applied per row over the table's whole
history.
- Age-only retention had no floor and could expire the table's CURRENT
snapshot, which is where fetchSnapshotInfo reads the incremental
watermark. At least the newest is always retained.
- `keep-last-snapshots: 0` no longer disables an accompanying age policy.
- quoteIdentifier emitted THREE quotes for an embedded quote; the snapshot
predicate and the catalog literals were unescaped while the expression
beside them escaped.
- The cursor fallback erased previousSnapshotId too; only the timestamp is
type-incoherent, and the id is independently documented.
Signals
- The supervisor returned after ONE signal. If that signal arrived before
Crow assigned its server, stop() was a no-op, stopped_ latched, and no
supervisor remained to read a second byte - terminable only by SIGKILL. It
now loops until the write end closes.
- The pipe write fd is an atomic, cleared before the close, and read once
into a local in the handler - otherwise a signal could write into an fd
number teardown had already closed and something else reopened.
Other
- config_service's template/expand and template/test were the third copy of
the `__auth_*` invariant and the only one without the guard - and
template/test EXECUTES what it renders.
- check_crow_response_fields.py now FAILS when it cannot find the crow
header, and runs in the job that has a build tree. It was in the
integration job, which only downloads the binary, so the guard protecting
the Arrow corruption passed vacuously on every run.
Tests
- The age-based retention test never asserted a's own snapshots went away,
so it passed if the expire CALL threw (caught and logged at WARNING).
- The shared-snapshot test's assertions sat behind `if (!expire.empty())`.
- The watermark section asserted arithmetic over constants the test wrote;
it now re-derives max(cursor) from the table.
- The heartbeat test's only evidence was "still answering"; it now requires
heartbeat activity in the log first.
- The refusal test could only reach the auth branch for the three mutating
tools - the ones where fabricated success was worst. There are now
token-bearing tests for them.
- test_ducklake_scheduler's `if True:` scaffolds are gone and its comment
matches the code.
768 unit green; all four invariant guards pass.
Co-Authored-By: Claude Opus 5 <[email protected]>
Crew round 4, unanimously across all four members: wiring the config tools to
their real handlers was right, but it made twelve tools that had been
classified "read-only discovery" genuinely powerful while leaving them
unauthenticated. Three were disclosures the moment they started working:
flapi_get_environment the VALUES of every whitelisted environment
variable - the same class TemplateSecrets was added
in the previous commit to redact;
flapi_expand_template the rendered SQL, i.e. whatever the template
interpolated from conn.* and env.*, through a path
needing no _dryRun flag;
flapi_test_template EXECUTION of any endpoint's template with
caller-supplied parameters - including endpoints
behind an auth: block and endpoints never exposed as
MCP tools - and with the RequestValidator layer
skipped entirely.
Every equivalent REST route is behind the config-service token. So every
flapi_* tool is now too; tokenMatchesConfigured fails closed, so with no
config service configured they decline, which is correct. "Read-only" was
never the right axis: reading a secret is a disclosure, and reading rows is
what an endpoint's auth exists to control.
Defence in depth alongside it:
- testTemplate runs the endpoint's own validators before executing, so a
test route is no longer a way around an endpoint's constraints.
- expandTemplate scrubs its output with the same collector the dry-run
preview uses, and withholds when a value is too short to replace.
- The audit query's endpoint filter is quote-doubled; a parameterised
endpoint like /orders/:id matches "/orders/x' OR '1'='1", so it was an
injection point.
A shutdown latch that made the process SIGKILL-only
APIServer::stop() set stopped_ and returned early on every later call, but
Crow's app.stop() is a no-op until run() has assigned its server. A SIGTERM
in the startup window therefore drained the pool, latched, and stopped
nothing - and run() then served with a shut-down pool, so every request got
503 forever while a second SIGTERM returned at the latch. The supervisor
loop added last round could not help. stop() now records the request, run()
refuses to start when it is set, the drain happens once, and app.stop() is
re-issued on every call.
Also
- withhold() no longer fires on caller-supplied params. Round 3's finding
was answered by changing the wording, not the mechanism: `?token=ab` still
blanked every error an endpoint could produce, on all three surfaces. A
value the caller sent is not a secret to withhold from them; it is still
scrubbed out of rendered output. Server-sourced defaults keep the old
treatment.
- The OUTER resources/read catch returned e.what() verbatim; only the inner
one had been scrubbed.
- flapi_run_cache_gc's "all cached endpoints" form never worked - the
handler's first act is getEndpointForPath(""). `path` is required, and the
description says so.
- Every tool declares its arguments. They all shipped
`{"type":"object","properties":{}}` while a separate table enforced
required ones, so an agent reading tools/list called with {} and got
-32602.
Tests
- template_secrets_test.cpp: 15 cases pinning both boundary constants, the
caller-vs-server provenance rule, and publicErrorMessage. The file sat on
three hot paths with no unit tests at all.
- Unauthenticated negative tests for every flapi_* tool, and for the three
disclosures by name.
- flapi_refresh_cache is asserted to leave a trace in the audit log rather
than to "return something".
- A test that every tool requiring an argument declares it, and that the
declaration matches what is enforced. Writing it turned up my own wrong
assumption - MCP returns tool errors as `isError: true` in a successful
response, not as a JSON-RPC error - which had made a perfectly good
validation rejection read as acceptance.
780 unit green; config-tool suites 52 + 17 + 17.
Co-Authored-By: Claude Opus 5 <[email protected]>
…nd test it
The rest of crew round 4.
The scrub belongs at the boundary, not at nineteen call sites
ConfigToolAdapter::fromHandler now scrubs every delegated failure body,
because a handler's error can quote the statement that failed - the rendered
template. That was about to become the fifth per-site copy of the same
invariant, which is the failure mode this whole round exists to break. It
also synthesises a body when a handler succeeds with an empty one
(refreshCache returns a bare 200), so an agent cannot mistake success for a
broken tool.
Environment values are redacted where they are produced
ProjectConfigHandler::getEnvironmentVariables returned every whitelisted
variable's value verbatim. It was written for a token-gated REST route and
then an MCP tool was wired to it. It now answers whether a variable is SET,
redacting credential-named and long values - a caller asking "is API_KEY
configured?" never needed the key. Ordinary configuration (a region, a
bucket) stays visible, because that is what operators debug with.
flapi_get_template returned a filename, not a template
It reported "Template retrieved" alongside the template's SOURCE PATH and
never its content. It survived the fabrication sweep because it returns real
data - just not the data it promises. Delegated.
Tests, all verified red against the pre-fix code by reverting and rebuilding:
- The config tools cannot be used as a second door to the secrets
test_mcp_dry_run_secrets.py already seeds. Against the unauthenticated
build this is unambiguous: flapi_test_template EXECUTED the template and
returned the connection password and the env key in its result rows.
Written first with the config service off, where they passed trivially
because no flapi_* tool existed to leak anything - fixed, and the sweep
keeps the version with it off as its own assertion (no config tools are
advertised when the service is disabled).
- handler_pool_test.cpp covers the drain budget abandoning the queue and a
second shutdown() waiting for the first rather than returning early - the
two behaviours the previous rounds introduced with no test at all.
- cache_manager_test.cpp covers keep_last and max_snapshot_age TOGETHER,
which is the pair the examples ship and the semantics this round changed:
ranking over the whole history, the age policy protecting a recent
snapshot, keep_last:0 not disabling an age policy, and the newest snapshot
never being expired.
- check_crow_response_fields.py now also requires the completion lambda to
write each field back. take() is only half the hop, and the original bug
was a field never reaching the response.
- test_an_unauthenticated_read_tool_still_works asserted the opposite of
what is now true and is inverted, with the reasoning recorded.
780 unit green; dry-run-secrets 20, config-tool-auth 17.
Co-Authored-By: Claude Opus 5 <[email protected]>
…h a floor
The remainder of crew round 4, plus two open questions it could not settle,
answered empirically against DuckDB 1.5.5.
A dropped and recreated cache table could never expire again
The exclusivity filter asked "touched none of THIS table's keys", so a
recreated table's older snapshots - which still carry the previous
incarnation's table id - looked like another table's data forever. Every
refresh then logged "N snapshots are shared with another cached table",
which was false and masked genuine sharing.
Verified: after DROP+CREATE, ducklake_table_info lists ONE row for the live
table while ducklake_snapshots keeps the old id in `changes`. The filter now
asks "touched no other LIVE table", so a dropped table's id is nobody's data
to protect. (That measurement also answers the review's other open question:
a recreated table does NOT produce two rows, so it cannot falsely trip the
ambiguity guard.)
Ambiguity means different things on the two paths
tableChangeKeys returning {} for a name held by two schemas is right for
expiry - acting on a guess deletes another endpoint's data - and wrong for
the watermark lookup, where it silently downgraded every refresh to a full
load: one silent failure traded for another. It now takes `strict`, and the
read-only path keeps its pre-existing best-effort behaviour.
Sibling tools resolved endpoints differently
flapi_expand_template / flapi_test_template / flapi_update_template used
pathToSlug + exact slug matching while flapi_get_template and every cache
tool used getEndpointForPath, which pattern-matches path parameters - so
{"endpoint": "/orders/123"} worked on one and 404'd on its sibling. They all
resolve the endpoint, then ask it for its own slug.
Sweeps with a floor and a deterministic order
The tools/list sweeps had no minimum on how many tools actually answered, so
a build where every tool errored passed them cleanly - the headline tests
for the headline change, unable to tell "implemented" from "always fails".
They now require a floor. They also iterated an unordered_map-derived list
and called flapi_delete_endpoint somewhere in the middle, so which tools
were really exercised varied per build; the order is sorted now and
destructive tools run last.
783 unit green; config-tool suites 17 + 53.
Co-Authored-By: Claude Opus 5 <[email protected]>
A secret under four characters cannot be replaced in rendered SQL without corrupting the text around it, so flAPI withholds error detail and dry-run previews for every endpoint using that connection - and there is nothing in the response to say why. The operator now learns once, at startup, through the same security-warning channel as the plaintext-password and unauthenticated- MCP warnings. The warning names the KEY and never the value, and is asserted on both counts. Co-Authored-By: Claude Opus 5 <[email protected]>
…ubbed SQL
Crew round 5. The first item is a data-loss path introduced by the previous
commit and flagged independently by three of the four reviewers.
liveTableChangeKeys failed open
It returned an empty vector on any error, and expirableSnapshotIds could not
tell "the catalog holds no other table" from "I could not ask". Empty meant
no foreign keys, which made the exclusivity predicate `true`, which classed
EVERY snapshot touching this table as exclusive and named it in
ducklake_expire_snapshots. A transient introspection failure during one
endpoint's refresh could therefore expire a snapshot shared with another
endpoint - deleting its data. Its sibling tableChangeKeys(strict) was
deliberately written to fail closed for exactly this reason; the two
disagreed.
It now returns std::optional, and retention expires nothing when the
listing did not succeed.
It also collected only numeric table ids, although `changes` names a table
by `schema.table` for creates - so a transaction creating this table
alongside another looked exclusive, because the other table's create key was
never in the foreign set. Both forms are collected now, the qualified names
via duckdb_tables() (ducklake_table_info exposes schema_id, not a name).
Errors were scrubbed before being returned but not before being LOGGED
REST, tools/call, resources/read and the config-tool boundary all logged the
raw e.what() first. A DuckDB error quotes the failing statement, and logs
are shipped, indexed and read by people who are not entitled to the
credentials a template interpolated. All four scrub first.
Tests
- Retention expires nothing when the catalog cannot be listed - red against
the fail-open version.
- "Every flapi_* tool declines without a token" as a PROPERTY over
tools/list rather than two names. Verified by flipping one flag back to
false: the sweep names it immediately. The paired test asserts a valid
token gets every tool past the gate, which is the exact property rather
than a count of successes.
- --config-service with NO token configured: every tool declines, for every
token including the right-looking one. That is tokenMatchesConfigured's
fail-closed branch, which existed because the original defect accepted
`Bearer anything-at-all`, and which nothing tested.
The CHANGELOG's shutdown claim is corrected: the budget bounds the QUEUE, not
a query that is already executing. flAPI does not cancel a running query, so a
hung backend can still delay shutdown until the platform's grace period. Three
consecutive reviews read the old wording as promising more than it delivers.
783 unit green; config-tool-auth 20, dry-run-secrets 20.
Co-Authored-By: Claude Opus 5 <[email protected]>
…artup race
Crew round 5's blocking set, completed.
`aged` absent read as "old enough" (the sibling of the live-table bug)
The age check was `!row.has("aged") || ...`, so a result without the column
made every snapshot eligible for expiry - the same fail-open shape as
liveTableChangeKeys, one loop away from it, on the same destructive path.
Fixing one and leaving its sibling is the pattern these rounds exist to
break. Absent now aborts the cycle with a warning, and a mock that omits the
column proves it.
expandTemplate?include_variables=1 returned the raw context
Three lines after the scrub that exists to keep conn.* and env.* out of the
response, this block handed back every context value verbatim - so the query
parameter was a complete way around it, on the REST route and through
flapi_expand_template. Every value now goes through the same TemplateSecrets
policy.
The SIGTERM-during-startup window
Checking `stop_requested_` at the top of run() is necessary but not
sufficient: signal_clear(), the bind and Crow's own setup all happen after
it, and Crow's `app.stop()` is `if (server_) server_->stop();` - a no-op
until run() publishes the server. A signal in that window drained the pool,
stopped nothing, and left a process serving 503 for the rest of its life.
run() now uses run_async() + wait_for_server_start() and re-checks once Crow
is actually stoppable.
Honest about the test: it sweeps the window at six delays, and against a
deliberately slow-starting config (DuckLake warmup with twelve cached
endpoints), and it does NOT reliably go red against the pre-fix build - the
window is about a millisecond and where startup has reached at a given
moment varies per run. The fix rests on reading Crow's app.h, not on a red
test. The test is a regression net, and it does pin the two outcomes that
are acceptable - exit 0, or death by SIGTERM before the handler is installed
- against the one that is not, a process that survives having drained its
pool. A second case covers two signals in the window, which the
handle-one-signal supervisor would have swallowed.
Also corrected: the CHANGELOG claimed the shutdown budget stops a slow query
holding a container open. It bounds the QUEUE; a query already executing is
still waited for, because flAPI does not cancel one. Three reviews read the
old wording as promising more than it delivers, so it now says what it does
and what it does not.
783 unit green; offload suite 19.
Co-Authored-By: Claude Opus 5 <[email protected]>
…ry tree Round 5 said this guard "cannot see the case its own docstring promises to catch". Both halves were true, and fixing them found two real gaps. It matched member declarations with one regex, so a member the regex did not match simply did not exist as far as the guard was concerned - and noticing a member it has not seen before is the guard's entire purpose. It now walks the struct body brace by brace and treats anything it cannot classify as a finding. That immediately surfaced `file_info`, which the old parser had never seen. It is private in crow::response and writable only through set_static_file_info(), which flAPI never calls, so it is a documented exception rather than a carry - the Completer could not copy it if it wanted to. It also globbed `build/**/crow/http_response.h` and inspected whichever copy came first. There are four trees here, and it was reading one the binary was not built from: adding a member to build/release's header left it green. Every tree is now checked, each independently - a stale tree may legitimately predate flAPI's crow overlay patch - and that surfaced the second field, `connection_keepalive`, which exists only in the patched tree. It is flAPI's own, and the Completer captures the keepalive directly rather than copying it off a local response, so it is an exception too. Verified by adding a member to one tree's header: the guard names it and the file it is in, and exits 1. NOT_CARRIED entries require a reason, so the next field cannot be waved through silently. 783 unit green. Co-Authored-By: Claude Opus 5 <[email protected]>
__auth_* strip finally has a test
Connection properties were judged by credential NAME only, while whitelisted
environment values also got the opaque-value rule - so a property called
`service_account`, `sas` or `credentials_json` carried a secret straight past
the stem list. Both are server-configured; both get the same rule now, with an
exemption for a value that is plainly a path or a URI, because `path` and
`database` are exactly what an operator reads a preview to confirm.
And the config service's template/expand and template/test routes - the third
copy of the "`__auth_*` is server data" invariant, and the only one that
EXECUTES what it renders - had the guard added last round with no test.
Against a build with the strip removed the spoof is unambiguous:
{"rows":[{"who":"admin","roles":"admin","authed":"true"}],"success":true}
returned by template/test, which ran that query. Three cases now cover expand,
test, and that an ordinary parameter still reaches the template.
783 unit green; auth-context 16.
Co-Authored-By: Claude Opus 5 <[email protected]>
…eir point
fromHandler's scrub was opt-in and most delegated tools passed nothing, so
"centralised at the boundary" was true of the code and false of the behaviour.
No secret set now means an OPAQUE 5xx - nothing there can be shown safe to
quote - while a 4xx, which names what the caller got wrong and cannot carry a
rendered template, stays actionable. Every endpoint-aware tool passes its
endpoint's secrets, so those keep full detail.
Connection properties now get the opaque-value rule that whitelisted
environment values already had: both are server-configured, and a property
named `service_account` or `sas` carries a secret past any stem list. A value
that is plainly a path or a URI stays visible, because `path` and `database`
are what an operator reads a preview to confirm.
tool_unimplemented_ is gone. It was added when eleven tools fabricated
results, emptied when they were wired to their real handlers, and then sat
declared, guarded and never populated - machinery no test could reach. The
invariant survives where it belongs: getRegisteredTools() does not advertise a
tool with no handler.
Four tests that could not reach their own assertions:
- The double-shutdown test instrumented only the second caller, so it caught
the early-return regression about half the time. Both callers are
instrumented and ordered now: re-verified against the pre-fix code, red on
3 runs of 3 where it used to be intermittent.
- The drain-budget test raced on wall-clock; a zero budget makes the
deadline already past when shutdown records it. Stable over 5 runs.
- The REST/MCP cache parity test used an endpoint with no cache, so it
always took the "both refuse" branch and its equality assertion - the
whole point - never ran. It now uses a cached endpoint, and a second case
covers the uncached one, asserting AGREEMENT rather than prescribing an
answer (both surfaces return `enabled: false`, not an error).
- test_no_config_tool_is_advertised_when_the_service_is_off never checked
advertisement. It does now.
786 unit green; config-tool suites 90, auth+secrets 41.
Co-Authored-By: Claude Opus 5 <[email protected]>
… at rest
Crew round 6. Three of its four high-severity findings are in code the
PREVIOUS round added - which is the whole argument for another round.
A hang I introduced, worse than what it replaced
run_async() + wait_for_server_start() closed the SIGTERM-during-startup
window and opened a bigger one. Crow constructs its Server - which BINDS in
its member-initialiser list - and only then calls notify_server_start(). So
EADDRINUSE, an unresolvable bind address or a failed validate() throws
before server_started_ is ever set, and wait_for_server_start() blocks on a
condition variable with no predicate and no deadline. Nothing wakes it:
app.stop() is a no-op with no server. Before run_async this threw
synchronously and the process died loudly.
Measured on the pre-fix build: a second instance on a bound port hung, and
`timeout 25` could not kill it - it outlived its own SIGTERM, which is
precisely the unrecoverable state. With the fix it exits 134 with
"bind: Address already in use". The wait now watches the future alongside
the start, and ends with serving.get() so a startup failure is raised
rather than discarded.
The location exemption re-opened credential disclosure
addConnectionProperty skipped the opaque-value rule for any value with a
'/' or '://' - which is the shape the credentials cloud deployments
actually use: `postgresql://alice:hunter2@db/prod`, an Azure SAS URL, an S3
presigned URL. None of `database`, `url` or `endpoint` matches a credential
stem, so all three reached unauthenticated dry-run previews and error
messages verbatim. My own test pinned it as desired behaviour.
The exemption is now the narrow case it was meant to be: a plain path, or a
URI with no userinfo and no query string. Three new cases cover the three
shapes above.
A credential written AT REST into the audit table
A failed refresh recorded the raw DuckDB error - which quotes the rendered
cache template - into cache.audit.sync_events: DuckLake Parquet files,
often on object storage, durable, backed up, time-travelled, and readable
through GET .../cache/audit and flapi_get_cache_audit. Every other copy of
the rendered statement was scrubbed on its way out; this one persisted it,
which is strictly worse than the log leak fixed beside it. Both the refresh
and GC paths scrub before recording now.
Also
- Secret replacement was insertion-ordered, so a short secret that is a
prefix of a longer one consumed its start and left the tail visible
(`<redacted>supersecret`). Longest-first, tested in both insertion
orders.
- liveTableChangeKeys silently skipped rows it could not read and still
reported success - the same fail-open one level down. Any unreadable row
now aborts the cycle.
- That change immediately failed a retention test, exactly as round 6's
reviewer predicted: the mock answered duckdb_tables() with a table_id, so
its name listing was malformed. The mock is faithful now, and a new case
injects a genuinely malformed row.
788 unit green.
Co-Authored-By: Claude Opus 5 <[email protected]>
…__auth_* The rest of crew round 6. ConfigService::validateToken compared `token == auth_token_` - not constant time, and TRUE when both are empty. The empty case is NOT reachable through the CLI (main generates a secure token when --config-service is given without one), so the explicit guard is defence in depth rather than a closed hole, and the test says so: it covers what IS reachable - an empty or absent bearer against a real secret, and a token one character short. The comparison is CRYPTO_memcmp now, like its MCP twin. I wrote that test's first version claiming it closed an exploitable fail-open. It passed for a different reason than the docstring gave, which is its own kind of test that cannot fail; both are corrected. DuckLake's metadata-path and data-path now go through the secret collector. A metadata-path is frequently a DSN with inline credentials or an object URL with a signature, and a failed refresh quotes the statement that attached it. The cursor watermark is returned RAW again. Pre-escaping it was wrong twice over: the docs say the value is rendered raw, and the documented double-brace form HTML-escapes what it is given, so `ab''c` rendered as `ab''c`. Escaping belongs at interpolation, where the template author already chooses the quoting - the docs now say to use the triple-brace form inside a SQL literal. And the `__auth_*` rule has ONE definition. It had five copies - REST read, REST write, the MCP tool path, and the config service's template/expand and template/test routes, the last two added only after a review found them missing, one of which EXECUTES what it renders. Every re-opening this area has had came from fixing one site and missing a sibling, so check_auth_prefix_single_source.sh fails the build on a sixth literal. Verified by adding one. 788 unit green; auth-context, dry-run-secrets and config-tool-auth 59. Co-Authored-By: Claude Opus 5 <[email protected]>
…redacted Round 6's low-severity sweep. `pass`, `user_pass`, `db_pass` and the Azure shared-access signature `sas` are real credential key names and none of them contains "password", so none was recognised. Added as substring stems they immediately swallowed `passenger_count` - which the ordinary-field-names test caught on the first build, doing exactly the job it exists for: over-redaction is the safe direction but it still costs real observability, and a stem that eats ordinary data-API field names is a bad stem rather than a cautious one. So the short ones are matched on the whole normalised key, with the prefixed forms that actually occur listed explicitly. `service_account` stays a substring stem, because it is long enough not to collide. A new test pins both directions: the eight names that must match, and five - `passenger_count`, `passengers`, `compass`, `sassafras`, `passage` - that must not. 788 unit green; the full integration suite 785 passed. Co-Authored-By: Claude Opus 5 <[email protected]>
Crew round 7. Design's verdict was "releasable from a design standpoint"; these are its findings worth doing before the release rather than after. isAuthenticationRequired() returned false for an unknown tool, commented "Default to no auth required for safety" - the opposite of safe, and a direct contradiction of this release's rule that every flapi_* tool needs the config-service token. A tool registered without an auth decision was public. It fails closed now and logs the programming error. executeTool asked the same question with tool_auth_required_.at(), which throws out of a scope no catch covers; it calls the one accessor instead, so the two cannot disagree. MCPDryRun had become a facade over TemplateSecrets with dead parts: hasUnscrubbableCredential and scrubConnectionSecrets had zero callers anywhere, MCPDryRun::scrub was a one-line forwarder, and `using Secrets = TemplateSecrets` gave one concept two names - with the doc block for a deleted function left dangling above the alias. All removed; the two MCP sites use TemplateSecrets directly. cache_manager.hpp - the design record for the subsystem re-opened most - had accumulated doc rot from this round's own rewrites: the deleted buildCountBasedExpireSql's doc above escapeSqlLiteral, tableChangeKeys' doc above fetchCursorWatermark, tableSnapshotPredicate still citing a function that no longer exists, and a "by value" note on the wrong parameter. A reviewer reading that header was told the wrong thing about three functions on a destructive path. And the bind-failure path detached the waiter thread while it held a reference to a promise living on run()'s stack frame. Unobservable today because the escaping exception terminates first, but it is UB that depends on main never wrapping the server thread in a try. It is a shared_ptr captured by value now. Re-verified: a second instance on a bound port still exits 134 with "bind: Address already in use" rather than hanging. Left for follow-up, reasoning recorded in the review: collapsing the three parallel tool maps into one RegisteredTool (which makes the fail-open default unrepresentable rather than checked), moving collectTemplateSecrets inside fromHandler to delete eight copy-pasted preambles, and a shared resolveEndpointArg() so the path guard applies once rather than to 5 of 13 tools. 789 unit green; full integration suite 787 passed. Co-Authored-By: Claude Opus 5 <[email protected]>
…I opened
Crew round 7, security: REQUEST_CHANGES, and correctly.
Round 6 removed the escaping from the cursor watermark, with a justification
that was right as far as it went - the documented double-brace form
HTML-escapes what it renders, so a pre-escaped value arrives mangled - and a
claim that was not: "cursors are timestamps, sequences or dates".
CacheConfig::CursorConfig::type is a free-form string and CONFIG_REFERENCE
explicitly blesses a string cursor.
So: an endpoint caches a source whose cursor column is a VARCHAR carrying
partly upstream-controlled text - a page token, an etag, an external version.
One refresh ingests a row whose cursor value is
x' UNION SELECT * FROM read_csv('/etc/passwd') --
that value becomes max(cursor), and the NEXT refresh renders it into the cache
template and executes it on the DuckLake connection, which has ATTACH,
COPY ... TO and read_csv of local files. Second-order injection, entered
through ordinary data, executed by a background job.
Validation rather than escaping, which is what makes it compatible with the
reason the escaping was removed: a value that passes needs no escaping, and
one that fails is DROPPED, putting the refresh on the full-load branch the
code already has and already tests. Timestamp/date/time and the numeric types
accept only the characters they are made of; anything else, `string` included,
rejects quotes, semicolons, comment markers, backslashes and newlines.
Tested both as a predicate (five sections, including the seven hostile shapes)
and through the PIPELINE - a real DuckLake cache table whose max cursor value
is the injection above, asserting the watermark never reaches the template,
with a companion case proving an ordinary string cursor still produces one so
the first cannot pass by rejecting everything. Red against a build with the
check disabled.
790 unit green.
Co-Authored-By: Claude Opus 5 <[email protected]>
…-7 items
The waiter thread was the wrong shape, and proving it took two tries.
Round 6's `wait_for_server_start()` blocked forever when crow failed to start.
Round 7 watched it from a helper thread - which answered that, and introduced
a third problem: on the failure path the helper can NEVER be woken, because
crow's notify_server_start() is private. It was detached, left blocked on a
condition variable that ~Crow then destroyed. Adding a try/catch in main
turned the loud SIGABRT that had been masking it into a silent HANG that
ignored SIGTERM - measured, twice.
There is no thread now. The future is polled, and app.stop() is re-issued on
each tick while a stop is pending: harmless before crow publishes its server,
effective from the moment it does. That answers both original questions - a
startup failure and a stop-during-startup - without anyone needing to detect
WHEN crow became stoppable, which is the thing that could not be done safely.
Measured: a second instance on a bound port now exits 0 with "the server could
not start: bind: Address already in use", having drained cleanly. Previously
SIGABRT, and before that a hang.
Four smaller findings from the same round:
- TemplateHandler::testTemplate returned "SQL execution error: " + e.what()
raw. It is the one config-service route that EXECUTES the rendered
template, so DuckDB quotes the statement - and expandTemplate 180 lines
above already scrubs, and getEnvironmentVariables redacts at the same
privilege level. The policy was inconsistent inside one file, on its most
dangerous route.
- /api/v1/_config/health is the only _config route without a token, and it
published every VFS backend's path and raw error. A storage path can
carry inline credentials or a signature - which is why DuckLake's paths
were added to the secret collector. Unauthenticated callers now get
status, scheme and latency; the detail is a token away.
- Config tool definitions were assembled by concatenating name and
description into a JSON literal, so a quote or backslash in either made
the parse fail and the tool silently vanish from tools/list: fail-open by
omission. Built as JSON now.
- `pw` and `key` recognised as whole-key credentials - a DuckDB S3 or HTTP
property is sometimes literally named that - with `pw_bucket`, `keyword`,
`sort_key`, `primary_key` and `monkey` pinned as unaffected.
791 unit green; offload 19, config suites 93.
Co-Authored-By: Claude Opus 5 <[email protected]>
…changelog `test_https_config.py` looked up the binary at the relative path `build/release/flapi`. pytest runs from `test/integration`, so it never resolved and all eleven tests skipped with "flapi binary not found" - since the file was written. The final pre-release suite run is what surfaced it: 7 of the 32 skips were this one file. Resolved from the repository root, four of them failed. Not because of HTTPS: every config in the file omits `project-description`, which is required, so each run died on that instead - and the negative cases, which assert only that validation FAILED, could not tell the two apart. They would have passed against a binary with no `enforce-https` validation at all. With the key supplied, all eleven pass and now test what they are named for: a scalar `enforce-https` is rejected, a cert without a key is rejected, an empty cert path is rejected, and a valid pair validates. Changelog for what rounds 5 to 7 changed for users: the unauthenticated `/api/v1/_config/health` disclosure, whole-key credential recognition, the startup warning for a credential too short to redact, watermark validation, retention failing closed, and a failed bind that used to hang. Full suite green the way CI runs it: 787 passed, 32 skipped (now 25). Co-Authored-By: Claude Opus 5 <[email protected]>
This was referenced Sep 23, 2026
`bun --compile` does not resolve the `file:./shared` dependency, so the
workflow rewrites `@flapi/shared` to a relative path first - in
`cli/src/lib/validation.ts`, by name. When the slug codec moved into
`@flapi/shared` and `cli/src/lib/url.ts` began importing it, that list went
stale and all four flapii targets failed to compile:
error: Could not resolve: "@flapi/shared". Maybe you need to "bun install"?
at cli/src/lib/url.ts:13:58
Rewrites every importer now, and fails loudly if there are none, or if one
appears outside `cli/src/lib` where `../../shared/src/index` would not resolve.
Co-Authored-By: Claude Opus 5 <[email protected]>
The integration-tests job downloads the `flapi` binary alone. It then ran
./scripts/check_cxx_standard_uniform.sh build/release
./scripts/check_tracing_abi_guard.sh build/release/libflapi-lib.a
against a `build/release` containing exactly that binary - no compile
database, no static library. Both scripts skip-and-exit-0 when their input is
missing, so both have reported success without checking anything, on every run
since they were written. This is the same defect as the crow-field guard,
which was moved to linux-build for the same reason earlier on this branch.
Two halves to the fix, because moving them alone would leave the trap armed:
- A path given on the command line is now a CLAIM that it exists. Both
scripts fail if it does not. Only the built-in default may skip, for a
developer who has not built yet. Verified: a nonexistent archive now
exits 1 where it used to exit 0.
- Both run in linux-build, where `make release` has just produced the tree.
The ODR guard runs on amd64 only - it reads mangled symbols with the
runner's own `nm` and the arm64 archive is cross-built; the property is a
source-structure one and is identical on both.
`check_crow_app_alias.sh` and `check_auth_prefix_single_source.sh` stay where
they are: they grep sources and need no build.
Co-Authored-By: Claude Opus 5 <[email protected]>
The shutdown self-pipe used `pipe2(fds, O_CLOEXEC)`. macOS has no such
symbol, so osx-universal-build failed outright on main.cpp:
error: no member named 'pipe2' in the global namespace; did you mean 'pipe'?
Linux and Windows were green - the Windows path is inside `#ifdef _WIN32`
and never sees it - so nothing local caught this.
`createCloexecPipe()` keeps `pipe2` on Linux and falls back to `pipe` plus
two `fcntl(F_SETFD, FD_CLOEXEC)` elsewhere. The only property lost is
atomicity against a `fork` racing from another thread, and this runs at the
top of main() before any thread or child exists.
The fallback branch was compiled and exercised on its own (-Wall -Wextra
-Werror) rather than assumed: both ends come back with FD_CLOEXEC set and a
byte round-trips. 791 unit green; offload suite 19 green on the rebuilt
binary, including the signal-delivery cases that use this pipe.
Co-Authored-By: Claude Opus 5 <[email protected]>
Contributor
Author
|
CI green on
Two CI defects were found and fixed along the way, both of the same kind this branch is about — a check that had never actually run:
And one portability defect: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The release candidate for
v26.09.23: #120's async offload, the F9/F10/F13 fixes from #140, andthe work needed to make both of them actually shippable.
#137 and #140 could not be merged as they stood — both had failing integration CI, for
exactly the defects fixed here:
test_arrow_streaming.pyfailures. The offload'sCompletercarriedcode/body/headersacross the thread hop and droppedcompressed, so Crow gzipped everyArrow IPC payload while its explicit
Content-Lengthdescribed the uncompressed size. Everyclient read a truncated stream.
test_ducklake_scheduler.py(a pre-codec slug, pointed at the uncached endpoint, with everyassertion behind
if status_code == 200).This PR therefore supersedes both. Closes #120, #123.
What is in it
Seven crew review rounds produced 60+ findings; all are fixed. Every round after the second
found a real defect in the previous round's fix — the recurring charge being that a fix landed
on the named instance and left its siblings, or closed a hole and opened a smaller one. So the
fixes here are made at the point where the siblings cannot diverge again, and four of them are
build-failing guards rather than edits.
Data loss and data disclosure
auth.*was unconditionally empty in every MCP template, on bothtools/callandresources/read. The documented{{#auth.username}}WHERE tenant = ...{{/auth.username}}filter therefore rendered nothing and returned every tenant's rows to any authenticated
caller. Strip-and-inject is now one function both surfaces call.
auth.emailhad the same gapand is now carried on MCP too.
endpoint reaching its limit destroyed every other endpoint's history and incremental watermark.
True of
keep-last-snapshots,max-snapshot-ageandflapii cache gc(which also ignoredthe configured policy in favour of a hardcoded one-day cutoff). All three now expire explicit
per-table version ids, and never a snapshot shared with another table.
permanently dropped the rows written during its own execution and reported success. It is now
max(<cursor>)over the rows actually cached._dryRunreturned connection passwords, whitelistedenv.*values and credential-valuedrequest defaults; so did the error path, which needs no
_dryRunflag to reach.Correctness
io_servicefor heartbeat-synthesised requests. The first fixrouted them inline to
handleDynamicRequest, which has the same dereference — so the crashmerely moved. Confirmed by core dump; the regression test that found it is new.
SIGTERMran the entire shutdown inside the signal handler, joining pool workers from whicheverthread the signal landed on. Now a self-pipe plus a supervisor thread, with
SA_RESTART, abounded drain, and Crow's own signal handlers disabled (asio's
signal_setwas replacing ours,which is how
~APIServerended up joining a worker during static destruction).flapi_*config tools reported success for work they never did, including one thatinvented audit records. "Is this implemented" is now a registration fact: such tools are not
advertised and are refused centrally.
Tests that could not fail — a name-list test that claimed to be property-based (and is why
four fabricating tools survived a round), three tests asserting only
result is not Noneagainstfabricated SQL, a suite with three independent reasons it asserted nothing, a unit test pinning
the catalog-wide expiry bug, and a tavern case for an unreachable route. All replaced with
assertions that discriminate.
Secrets, and the boundaries they cross (rounds 3-7)
TemplateSecretscollector now owns what a secret is - connection properties,whitelisted
env.*values, caller-supplied auth material and DuckLake storage paths - and onepublicErrorMessage()scrubs every config-service and MCP error that can quote rendered SQL.Previously each site decided for itself, and four of them decided wrong.
pass,pw,key,sasand friends matcha property literally named that, while
passenger_count,keyword,sort_keyandmonkeyareleft alone. A secret shorter than four characters cannot be scrubbed without corrupting the text
around it, so flAPI withholds the detail and says so at startup rather than silently.
flapi_*MCP config tools delegate to the real REST handlers and all require auth;isAuthenticationRequiredfails closed on an unknown tool. The REST token gate, theinclude_variablespath,expandTemplate,testTemplateand/api/v1/_config/healtheachleaked something and no longer do.
is interpolated into the next refresh's SQL - closing a second-order injection.
Guards added
scripts/check_crow_response_fields.pyfails the build ifcrow::responsegrows a field theoffload does not carry. A future Crow bump would otherwise reintroduce the Arrow corruption:
compiles clean, fails only at runtime.
make integration-test-cinow runs the tests. Its readiness probe was apython3 -cone-linerwith an indented block — a
SyntaxErrorthat killed the target before pytest, every time, soit had never run a single integration test.
Test plan
@flapi/sharedstatic-destruction race, which is a probabilistic regression net and is labelled as one
check_crow_app_alias.sh,check_crow_response_fields.py,check_cxx_standard_uniform.sh,check_tracing_abi_guard.sh,check_auth_prefix_single_source.sh(new: fails the build on a sixth"__auth_"literal)SIGTERMmid-request drains and exits 0; a second instance ona bound port now exits 0 with
bind: Address already in useinstead of hanging past its ownSIGTERMBehaviour changes to call out
auth.*will return different results — that is the fix.{{cache.previousSnapshotTimestamp}}is the cursor's own type when acursor:is configured,not a timestamp, and is absent (full-load branch) when no watermark can be read.
the server.
🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.