mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
kernel, validation: Add btck_chainstate_manager_set_clock_time #35557
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35557
Loading…
Reference in a new issue
No description provided.
Delete branch "pr/kclock"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem: Kernel applications can only override the time validation uses for the whole process, with
btck_set_mock_time(#35496). Every chainstate manager in the process sees the same time, so a time set for one test, run, or thread leaks into the others unless the application remembers to reset it.Solution: Add
btck_chainstate_manager_options_set_clock_timeandbtck_chainstate_manager_set_clock_time, which set the time for a single chainstate manager, before it is created (so it also applies to checks made while it loads the chainstate) and afterwards. Validation code gets the time from a newChainstateManager::Now()method instead of callingNodeClock::now()directly. Details are in the commit messages.Keeping the time in the chainstate manager instead of in a global makes kernel applications more reliable, because state from one run or thread can't affect another.
Other commits:
chainstatemanager_ibd_exit_after_loading_blockstest, where test code and validation code read the clock separately and assumed they got the same time.utxo_total_supplyfuzz target to the new per-chainman clock, as suggested in https://github.com/bitcoin/bitcoin/pull/35557#issuecomment-4763429282.Two related commits that were previously part of this PR are in a follow-up branch based on it, https://github.com/ryanofsky/bitcoin/commits/pr/kclock2: a mempool refactor to represent clock times consistently, and a change that makes
NodeClock::now()unavailable in libbitcoinkernel so kernel code can't use the system clock by accident.The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
A summary of reviews will appear here.
Conflicts
Reviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/27733525041/job/82045427048LLM reason (✨ experimental): CI failed because the IWYU (include-what-you-use) check reported changes needed (generated “Failure generated from IWYU”).
Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
9f67c9b269cbc0da459eafa1a5ba357e82f07212: You can use
tip->Time(), to avoid the cast here.Generally, it is better to use the chrono types and let the compiler do the type checks. After compilation, there won't be a difference anyway.
Seems fine, but this may be promoting ugly code, such as
count_seconds(DurationSinceEpoch<std::chrono::seconds>(...I think generally it is better to use the correct std chrono type and let the compiler do the type checks. Casting a time point to a duration (since epoch) seems like a violation that should be avoided, for the same reasons that
GetTimeis deprecated.At call sites you can just replace block->GetBlockTime() with block->Time() to avoid any casts, and this helper.
Do we really want the cast here? The answer is probably, "doesn't matter", because consensus time checks are seconds-based, and the double-precision rolling update mempool code doesn't care about sub-second precision. Though, I wanted to point it out, that this is intentional and not just something that was most likely to the LLM.
An alternative could be to remove the cast here and only add the cast in call sites that need it (implicilty "upgrading" the call-sites to sub-second precision)
Thanks @maflcko! I was very dissatisfied with all the casts in the second commit and your tips should be helpful for getting rid of them. I will also implement your suggestion to not cast away precision in ChainstateManager::Now(). (The LLM actually didn't write the cast, but called
::Now<NodeSeconds>()instead and I manually added the cast to try to be more explicit.)Updated 7d656ac341140dc80f73abcc45adc19f0430eaae -> 94622b041571f73e8e5e661b9bce4213b957a561 (
pr/kclock.1->pr/kclock.2, compare) adding a new commit to use time points to represent times in mempool codeUpdated 94622b041571f73e8e5e661b9bce4213b957a561 -> 27ea72916b71e40859d7d86348eb3d99c4211b34 (
pr/kclock.2->pr/kclock.3, compare) to fix CI: compile error (duration_cast on time_point in TRACEPOINT calls) and nondeterministic test (clock race in chainstatemanager_ibd_exit_after_loading_blocks); also prepends a standalone test fix commit using only pre-existing SetMockTime API https://github.com/bitcoin/bitcoin/actions/runs/27764264509/job/82146558123Updated 27ea72916b71e40859d7d86348eb3d99c4211b34 -> 8be500e6bec2e4e664f36dea22c6419237ba9ec2 (
pr/kclock.3->pr/kclock.4, compare) to fix fuzz UBSan signed integer overflow converting seconds to nanoseconds in ConsumeTxMemPoolEntry https://github.com/bitcoin/bitcoin/actions/runs/15491561394/job/82175291056Updated 8be500e6bec2e4e664f36dea22c6419237ba9ec2 -> 37fb1b596e2006ffb1af82945f81a27c2bc1777a (
pr/kclock.4->pr/kclock.5, compare) to fix UBSan signed-integer-overflow: throw in LoadMempool when nTime is out of MempoolTime range; also use ConsumeTime() in ConsumeTxMemPoolEntry https://github.com/bitcoin/bitcoin/actions/runs/27776901912/job/82191293065re: https://github.com/bitcoin/bitcoin/pull/35557#discussion_r3433180374
Thanks! That is so much better and I applied this many places
re: https://github.com/bitcoin/bitcoin/pull/35557#discussion_r3433217273
You're right, dropped this now
re: https://github.com/bitcoin/bitcoin/pull/35557#discussion_r3433238010
I don't think so. It's definitely simpler not to have this and it is dropped now.
I guess it's fair to blame the LLM for this. Technically I added this cast, but the LLM originally wrote
::Now<NodeSeconds>()which was casting internally. Smarter to avoid it entirely.probably not a problem in reality, but the call to
GetMockTimehere looks wrong for several reasons:0, and thus may lead to silent bugs if mocktime was not used here?g_used_system_timeruntime sanitizer.I guess it would be better to just call
Now()ortx_pool.Now()to fix all issues and avoid the NodeSeconds{} cast.Marked ready for review now that CI is passing. Possible questions for reviewers:
btck_chainstate_manager_set_clock_time(chainman, now)a good kernel API? I think it is, giving applications control over time in a pretty granular way that doesn't get in the way of adding more control later.ChainstateManager::m_clock_now_secondsfield which adds new state, but not much changes otherwise and the changes make code more consistent.re: https://github.com/bitcoin/bitcoin/pull/35557#discussion_r3436545216
Makes sense, switched GetMockTime() -> Now()
My preference is larger pull requests usually, so I would keep this in one piece, but I would go a bit further. Can we use this new clock in one of the tests (maybe one of the utxo* fuzz tests, haven't looked too closely yet).
If we set it in the options instead, we can fake the time once per instance, if we set it like here, it can be moved any number of times. I think I prefer that, as it seems to overlap more closely with the current global mechanics. The only reservation I have with this is that there might be a case where the clock needs to be set during chainman construction. I don't think that is the case right now, but that might change in the future.
I would feel more confident if something (a test, a utility, etc.) was actually exercising the various instances where the chainman-scoped fake time is used now.
This could get a bit annoying and potentially dangerous when users need to start managing clocks across multiple places. Perhaps a more ergonomic alternative could be to add a
btck_Clocktype which basically is just a callback that returns the current time? The callback can then be anything, e.g. a fixed value, the user's system time, a mocked clock, ...That way, a single clock can be passed multiple times, and updated in a single place. Of course, it comes with its costs of increased API surface and lifetime concerns that a simple seconds setter doesn't have.
In commit "test: Fix nondeterministic clock race in chainstatemanager_ibd_exit_after_loading_blocks" (f0fea79bdaabbea40f1177702ff2c169d82f62be)
Nice fix, thanks for cleaning this up.
Instead of bare
SetMockTimecalls, this is a good candidate for the RAIIFakeNodeClock.🚧 At least one of the CI tasks failed.
Task
Windows native, fuzz, VS: https://github.com/bitcoin/bitcoin/actions/runs/28340730799/job/83954616764LLM reason (✨ experimental): CI failed because the fuzz test corpus runner hit an error in the
utxo_total_supplytarget (fuzz.exe exit code 1 processing a specific input).Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
re: sedited https://github.com/bitcoin/bitcoin/pull/35557#issuecomment-4763429282
Thanks, kept all commits for now and added new tests as suggested.
re: stickies-v https://github.com/bitcoin/bitcoin/pull/35557#issuecomment-4780411600
This is an interesting idea. Implemented in 3d513c5d03ceb8d33dc8e19c07149e3337c64ac6 to see what it would look like.
The implementation barely even affects validation code so I think the main question is does it seem safer or easier to use for kernel applications?
My instinct is that it doesn't because if you're creating multiple chainstate managers or other objects that accept times, and your application needs artificial times instead of the current clock time, I wouldn't assume that multiple objects would want to have the same time set. Or if they did, I wouldn't assume that setting the time once on a shared clock object would be much easier than setting the time directly on the relevant objects.
But I also think this alternate API is clean, and would have no problem switching to this approach. It also seems like it wouldn't be hard to switch approaches later (with compatibly even).
Updated 37fb1b596e2006ffb1af82945f81a27c2bc1777a -> 1ae28a401368448cc6466aada72afe2101ae7d61 (
pr/kclock.5->pr/kclock.6, compare) adding suggested testsUpdated 1ae28a401368448cc6466aada72afe2101ae7d61 -> 12a237f9d3570f96663dd84550f9fcc25ee53584 (
pr/kclock.6->pr/kclock.7, compare) to fix utxo_total_supply fuzz g_used_system_time failure https://github.com/bitcoin/bitcoin/actions/runs/28340730799/job/83954616774re: https://github.com/bitcoin/bitcoin/pull/35557#discussion_r3471733323
Thanks! Applied your patch and switched to FakeNodeClock
🐙 This pull request conflicts with the target branch and needs rebase.
That one was merged, so is this here still relevant?
Also, this conflicts with https://github.com/bitcoin/bitcoin/pull/35906#discussion_r3726539086
🐙 This pull request conflicts with the target branch and needs rebase.
🐙 This pull request conflicts with the target branch and needs rebase.
2 additional verified findings in the full report.
Earlier concerns remain unresolved; see the full report for their current assessments.
🟠 Minor · Clarify whether the clock-time override is fixed or advancing
validation.h:1027 Now() returns the stored timestamp unchanged until the caller resets it. The public set_clock_time doc only says it 'overrides the current time' and never says the value stays fixed, so a long-running caller must keep advancing it.
Location:
src/validation.h:1027(head).🔵 Suggestion · Options-clock test does not protect load-time clock initialization
The test only observes header validation after construction, so installing the options clock after startup verification would still satisfy its assertions.
Location:
src/test/kernel/test_kernel.cpp:1607(head).🔵 Suggestion · Clock documentation omits override precedence and maintenance timers
Zero falls back to the global mock when set, nonzero overrides that mock, and periodic flush scheduling remains outside the scoped clock despite the broader documentation.
Location:
src/kernel/bitcoinkernel.h:1353(head).🔵 Suggestion · Clock tests do not check isolation between managers
The single-manager future-time assertions would also pass with shared clock storage, leaving the API's per-manager isolation unprotected.
Location:
src/test/kernel/test_kernel.cpp:1571(head).🔵 Suggestion · Fuzz clock comment names an absent helper and omits template creation
The retained global mock covers direct NodeClock reads in both flushing and block-template creation, not the nonexistent
_now_nondet()helper.Location:
src/test/fuzz/utxo_total_supply.cpp:39(head).🔵 Suggestion · Scoped-clock tests miss IBD, reset and callback-progress regressions
The IBD test does not reliably distinguish clock sources, and the kernel tests leave reset fallback and scoped callback progress unasserted.
Location:
src/test/validation_chainstatemanager_tests.cpp:192(head).Review coverage was incomplete.
Reviewed:
2f6b902f980a· Full review report · Previous reportspermalink
🐙 This pull request conflicts with the target branch and needs rebase.
I'm not sure. Some of the test changes seem fine, but not sure if this is worth the squeeze. Maybe @stringintech can chime in?
Thanks for the reviews, and sorry for the slow update. I made this PR smaller and added a way to set the time before the chainstate manager is created, which answers sedited's construction-time question. Replies to each comment are inline.
Updated
0e777d8b30->2f6b902f98(pr/kclock.11->pr/kclock.12, compare) addingbtck_chainstate_manager_options_set_clock_time(), using time point types for clock times, and moving the mempool refactor and the kernelnow()check to https://github.com/ryanofsky/bitcoin/commits/pr/kclock2re: sedited https://github.com/bitcoin/bitcoin/pull/35557#issuecomment-6415550075
In commit "kernel, validation: scope clock time to ChainstateManager" (
98bb3d3114)Thanks, that's fair, and the PR was trying to do too much. I made it smaller: it now has the test race fix, the
btck_chainstate_manager_set_clock_timeAPI (now with an options setter too, see the separate comment about construction time), and the two tests using the new clock (chainstatemanager_ibd_exit_after_loading_blocksand theutxo_total_supplyfuzz target you suggested). The mempool time point refactor and the commit makingNodeClock::now()a link error in kernel code are now in a follow-up branch based on this one: https://github.com/ryanofsky/bitcoin/commits/pr/kclock2. I know you suggested keeping this in one piece, so I can open the follow-up as a PR whenever that would help review.On maflcko's question in https://github.com/bitcoin/bitcoin/pull/35557#issuecomment-5313546704: I think this is still relevant. #35496 sets the time for the whole process, and this sets it for one chainstate manager, so a time set for one test, run, or thread can't leak into another.
re: sedited https://github.com/bitcoin/bitcoin/pull/35557#issuecomment-4763429282
In commit "kernel, validation: scope clock time to ChainstateManager" (
98bb3d3114)Looking again, there is one already:
btck_chainstate_manager_createloads the chainstate, which runs this future-tip check and can latch the IBD status off, before the caller can callbtck_chainstate_manager_set_clock_time. So I addedbtck_chainstate_manager_options_set_clock_time, which sets the time before the chainstate manager is created, and keptbtck_chainstate_manager_set_clock_timefor changing it afterwards, so the time can still be moved any number of times, as you preferred.re: maflcko https://github.com/bitcoin/bitcoin/pull/35557#issuecomment-5313546704
In commit "kernel, validation: scope clock time to ChainstateManager" (
98bb3d3114)The conflict with #35906 is only textual, and the two changes fit together: #35906 makes
ContextualCheckBlockHeadertake the time as a parameter, and with this PR its callers would passchainman.Now()instead ofNodeClock::now(). I'd suggest #35906 go first since it has ACKs, and I'll rebase on it.re: stickies-v https://github.com/bitcoin/bitcoin/pull/35557#issuecomment-4780411600
In commit "kernel, validation: scope clock time to ChainstateManager" (
98bb3d3114)One argument for your callback idea that I missed before: stringintech pointed out in https://github.com/bitcoin/bitcoin/pull/35496#issuecomment-5207535775 that a long call like
btck_chainstate_manager_process_blockmay need to read the time several times, for example when the IBD status is re-checked after each connected block. A fixed time set beforehand can't advance during the call, and a callback can. My prototype in 3d513c5d03ceb8d33dc8e19c07149e3337c64ac6 only made the time a shared settable value, so it didn't really test your suggestion. I still think a setter is simpler to start with, since a fixed time is what deterministic tests and replays want, but I'm happy to switch to a callback if you or others think it's worth the extra API surface.