mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 15:08:38 +00:00
refactor: Use NodeClock::time_point in more places #35315
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!35315
Loading…
Reference in a new issue
No description provided.
Delete branch "2603-net-less-GetTime"
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?
It is a bit confusing to have some code use the deprecated
GetTime, which returns a duration and not a time point, and other code to useNodeClocktime points.Fix all places in
net_processing.cppto properly use time_point types.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.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.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
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/26042826463/job/76558889400LLM reason (✨ experimental): CI failed because the build stopped with a Clang
-Werrorerror:rpcconsole.cpphas an unused variable (time_now).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.
Concept ACK
ACK fa14855ff1bd527cbbd56080eb2cfdcd74d780da
Tested ACK fa14855ff1bd527cbbd56080eb2cfdcd74d780da
In commit fa1a22927adac877c46645b586ecda8ae1592002,
peerman_testsstill has a few straightforward migrations left. Non-blocking, happy to send a follow-up if you'd rather not fold it in here.Yeah, the goal here is mostly to fix net_processing fully. Not sure what the ideal size of a pull request is, but 7 commits and ~150 lines explicitly touched (and a few more implicitly) seems ok-ish.
Edit: I think the next pull should just remove it fully, in all remaining places?
Perhaps it's useful for the next follow-up to avoid clashing with the scoped clock proposed for the kernel in #35557?
Code review ACK fa14855ff1bd527cbbd56080eb2cfdcd74d780da. But approach +0.5.
NodeClock::time_pointis an improvement over using integer or duration types to represent time points. But I don't think it's a good thing to be hardcodingNodeClock::epocheverywhere, especially for things like block times which don't come from the node/system clock. If default-initializing time variables, it seems better to do it the standard way by calling default constructors, instead of inviting inconsistency and preferring to use bitcoin-specificNodeClock::epochconstant. Also, if choosing sentinel time values, it seems better to use min or max values than to treat the epoch time as being special unnecessarily.I am also not sure it's good hardcode
NodeClock::time_pointtypes everywhere. It seems like a lost opportunity to choose to hardcode a platform-dependent clock type that doesn't have a standard precision or representation, when we could use application-specific type aliases likeusing MempoolTime = NodeClock::time_point;,using NetworkTime = NodeClock::time_point;,using BlockTime = NodeSeconds;to not be tied to the system clock and be able to intentionally chose which precision and representations to use in different areas of the code. For example, it would be nice to define standard ways of serializing each of these types without requiring them all to be serialized the same way.I left more detailed code review comments below, but I guess my main feedback is I would be happier to see most
NodeClock::epochuses dropped. And I also think it could be a good idea to replace mostNodeClock::time_pointreferences here with a networking specificNetworkTimealias.In commit "refactor: Use NodeClock::time_point instead of std::chrono::seconds" (fa72cdf9563a39d6253570199a594b40d14c65dd)
Commit title is very generic. Would be good to add "in node stats" to indicate where the replacement is happening.
In commit "refactor: Use NodeSeconds for m_best_block_time" (fa1a22927adac877c46645b586ecda8ae1592002)
This seems unnecessarily confusing. NodeClock is an arbitrary precision system clock while NodeSeconds explicitly uses integer second values. It doesn't seem helpful to mix up these different types and it is also just shorter to write
std::atomic<NodeSeconds> m_best_block_time{}.In commit "refactor: Use NodeClock::time_point instead of std::chrono::microseconds" (cccc80ec090257ad614e54ca3975004282531bd9)
The new code seems to make less sense semantically the old code.
The previous
if (state.m_stalling_since.count())reads like "if a stalling_since value is set".The new "if (state.m_stalling_since != NodeClock::epoch)" reads like "if not stalling since january 1, 1970"
Number of ways this could be improved:
m_stalling_sincetoNodeClock::time_point::maxinstead ofNodeClock::epochm_stalling_sinceusestd::optional.NodeClock::time_point{}default value instead referencing the unix epoch.In commit "refactor: Use NodeClock::time_point instead of std::chrono::microseconds" (cccc80ec090257ad614e54ca3975004282531bd9)
Would seem more consistent to use
NodeClock::time_point::min()here instead ofNodeClock::epochto indicate we are not syncing, given thatNodeClock::time_point::max()is used immediately below to indicate we are done syncing. Epoch time should not be relevant.In commit "refactor: Use NodeClock::time_point instead of std::chrono::microseconds" (cccc80ec090257ad614e54ca3975004282531bd9)
Would seem good to mention net_processing in the commit title since otherwise it is unclear what part of the codebase this commit affects.
In commit "refactor: Use NodeClock::time_point for m_last_block_announcement" (fa67c651510db5e571fa82fe692ac33e48c451a4)
Can commit message be clarified to say whether there is any change in behavior here? Presumably if times were previously represented in seconds, and now higher precision times are used, now comparisons between the times may return different values and new bugs and corner cases could be exposed.
Changing behavior should be ok and probably even an improvement, but commit message should clarify whether it is changing or not. Same comment applies to most other commits in this PR as well.
In commit "refactor: Use NodeClock::time_point in txdownloadman/txrequest" (fae925ff923f05f34c800b92039e5fd058262b74)
Not important, but since this commit moves away from hardcoding microsecond types everywhere, it would be nice for test code here to stop hardcoding microseconds as well and switch to ticks (
NodeClock::duration) instead.In commit "refactor: Allow NodeClock::epoch to be used in NodeSeconds context" (fa10abb29538fabb4ad97dd70a2e4c709f38fc16)
This change seems kludgy and would seem to encourage writing bad code.
The kludgy part is mixing up different
time_pointtypes inside a clock definition which should have one native time type.The bad code part is encouraging code that shouldn't be tied to the unix epoch to reference it unnecessarily. For example the code using
NodeClock::epochin this commit is storing absolute times as durations which we do not want and should not encourage. And code in later commits usesNodeClock::epochas an inappropriate sentinel value wheretime_point::min,time_point::max, orstd::nulloptsentinels would be more appropriate.Would recommend dropping this commit, if not deleting the
NodeClock::epochconstant entirely which seems nonstandard and not very helpful.If default time values are needed, it's more direct and less verbose to call the default time point constructor. Having this second bitcoin-specific way of default initializing time variables just makes code less consistent and more confusing.
Not sure. Those types are direct aliases, so they are tied to the (mockable) system clock (aka node clock). Also, given that they are type aliases, so anyone can use them interchangeably, which seems confusing.
While I like my approach, I don't think it matters much and I am happy to switch to whatever reviewers prefer.
Ok, I'll think about those over the next few days, mostly wondering how to minimize review churn on this.
Though, I think that it is nice to make the special value verbosely typed.
(same). I think it is easy enough to call
git show --statto see the area of the codebase, but I am happy to consider changing it if there is a push to this pull.I think that makes the commit message larger than the recommended 70chars, but I am happy to push this, if you think it is a blocker.
I don't think this is allowed. Changing the fuzz test values to something else will likely change the fuzz input format, which is a behavior change.
Changing the behavior is not allowed in refactor commits, according to
CONTRIBUTING.md:137I use the keyword
refactor:in the pull request title and in all commits to indicate that no behavior change is going on. If some weird or obscure behavior change was happening, it would be my burden to point them out in the commit message and reviewers are meant to be encouraged to report undocumented behavior changes.I like this notation, and I think it is brief and understandable. Also, it is explained in the docs:
However, if you think it is a blocker, I can modify all the commit messages to say:
I don't understand why this is confusing. The epoch of a clock is always the same (a compile time constant), regardless of the the clock's time point duration.
Yes, it is shorter, but also more confusing.
0sorepochis used as a sentinel value, so it seems good to be explicit about the special meaning.I know you mentioned that
std::optionalcan be used instead, which would be cleaner. However, I don't really agree here, because it would make the code a lot more verbose and every call-site would have to safely unwrap the optional one way or another (nestedif,value_or, ...)I like the current commit, so I think I'll keep it, but let me know if this is a blocker.
IIUC addrman is using that to detect corrupt data and also using that as a sentinel. Also, it is used in the addrman serialization. The alternative to serializing just the duration would be to also serialize the type (epoch) somehow, but I don't think a full addrman rewrite with an addrman serialize change is the right call for a simple refactoring change.
I am not sure if there is much value in removing the zero/echo stuff everywhere, but when epoch is used consistently, it is also easier to grep for it and find all places with a single call to
git grep.I like the commit, and I don't think it matters much, so I'd prefer to keep it. But I am happy to drop it, if you think it is a blocker. Also, I am happy to review a different pull removing
epoch(assuming that such a pull is doing some more important substantial changes as well)Thanks for the replies. I still think expanded uses of NodeClock::epoch in this PR are bad, and haven't seen a positive case being made for them. So would like to see that addressed by dropping them, improving them, or explaining benefits with some rationale.
re: https://github.com/bitcoin/bitcoin/pull/35315#issuecomment-4845161113
Not sure what is confusing. Type aliases are meant to be interchangeable. They exist to express developer intent and make code more readable and maintainable. Using them would make time variables declarations more self-documenting, allow changing time types without causing churn, and allow adding more type constraints or features like serialization support in the future. I don't have a strong opinion on this. I just think it is a good idea without any downsides that I can see.
re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3491970807
Looking at net_processing.cpp I see only one access in ApproximateBestBlockDepth which seems buggy and better off using std::optional.
You also claim that calling the default time point constructor (https://en.cppreference.com/cpp/chrono/time_point/time_point) would be "more confusing" without saying what is confusing. The default constructor is part of the standard and well-documented. NodeClock::epoch is nonstandard, undocumented, unjustified, and even more of an oddity after this PR because it now uses a different time type than the rest of the clock.
re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3492644922
Note: of the 3 suggestions, comparing against
NodeClock::time_point{}would be the smallest change, and would be a relative improvement because it would make code that is using an inappropriate sentinel value look like it using an inappropriate sentinel value. But other alternatives to use an appropriate value or use std::optional do not seem like much work either.re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3492350338
Thanks, anything seems fine. It is just nice to have to be have some idea about which code is changing when looking at git log --oneline output.
re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3499889472
Yes, that's my intent here. Comparisons like
state->m_last_block_announcement < oldest_block_announcementthat could previously be false when times were seconds may now be true when times are nanoseconds (in case where times were equal). So this change does not seem like a pure refactoring and it would be good to point out any possible behavior changes like this in commit messages.A similar case where switching to more precise time types caused an observable change in behavior is 77043b0c856f195bda051a1feb2505347f0eddf3. There are also cases where changing time types could lead to overflows, but I don't think that is happening here.
re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3499890163
I'm not suggesting changing the addrman serializaton format. That would be crazy. I am just asking to not increase usage of the unnecessary, nonstandard, undocumented NodeClock::epoch constant.
There is no enforcement NodeClock::epoch is used consistently. Bitcoin core is adding a new, nonstandard clock class member to reference january 1, 1970, and encourage using it as a magical time point without disabling
time_pointdefault constructor which also sets this time. If this change included a lint check to prevent the default time_point constructor from being used that could make more sense. But this change provides no extra safety while encouraging bad duration-based code and magic-constant code to be written.The other changes in this PR using time point more places seem great. But this change extending
NodeClock::epochto places where it doesn't actually make sense to treat January 1, 1970 as special is a step backwards. Better alternatives are using time_point::min, and time_point::max and std::optional in most cases.I would definitely encourage dropping it but if you don't want to drop it I would like to see some explanation of why it is good to have. It seems like the only use-cases are bad code.
NodeClock::epochis not mentioned in the PR description and no other reviewer has commented on it. It's referenced 10 times before this PR and 44 times after. I gave a code review ACK and half-concept ACK on the PR so this is not a blocker for me, but I would definitely like to see it dropped from the PR or properly explained.re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3491892049
Another possible approach you can take if you are not comfortable with changing existing code or using the default
time_pointconstructor for its intended purpose would be to define a standalone constant like:This would be a drop-in replacement for the new
NodeClock::epochdefinition in this PR and avoid the problems I thinkNodeClock::epochcreates of encouraging incorrect and unsafe code, since it has a scarier and usage comment. It would also avoid adding a nonstandard member to the clock class.Ok, I just fail to see how to change addrman to avoid this magic value of zero. It is deeply embedded, so any change away from magic-zero means a larger re-write.
I agree with you that epoch is unnecessary, but I think it is self-explanatory that it means the epoch (time-zero). Also there is a static_assert for documentation:
static_assert(NodeClock::epoch.time_since_epoch().count() == 0);Your suggested docstring looks nice. I am happy to modify the first commit to add that docstring to
epoch.I am less sure about moving this to a stand-alone constant. I can see your criticism, but I don't think
epochsimply existing is encouraging incorrect and unsafe code (compared to the alternative of having no docstring and just a std-lib default constructor without any docstring/warning). If moving to a stand-alone constant is important, maybe it can be done in a follow-up?Btw, I agree. It is just that I don't agree the constant itself makes it worse. This is simply a years-old pre-existing code pattern, and I don't want to expand the scope here too much. (The changes are already 7 commits and 150+ lines changed)
The other reviewers didn't seem to have flagged it either?
I don't think the bug was caused by switching to more precise time. The bug fixed there is a rare pre-existing bug, which was made more likely (almost deterministic) by using precise time.
Correct. C++ duration types can deal with year ranges of roughly +-292 years, according to https://en.cppreference.com/cpp/chrono/duration.
I'd presume, mostly there are only overflow issues, when using native time_point ::min() or ::max() in combination with untrusted input seconds (thus injecting a multiplication that overflows).
Correct, but this change in behavior is not reliable or observable from outside. In fact, the tie-breaker behavior on the peer-id seems questionable to begin with. If block announcement happened on a "second-boundary" on master, e.g a block is announced by peer N in second 2.99, but by peer N+1 in second 3.01 (difference 0.02 seconds), then peer N is evicted. However, if the same difference of 0.02 seconds happens some other time (like peer_N announces at 5.20s and peer_N+1 at 5.22s), then peer N+1 is evicted.
Happy to add this to the commit description, or happy to remove the code, but I wouldn't remove the
refactor:label, as I don't consider this a change of behavior. Though, I can also add back the cast to seconds explicitly, if you think it makes sense.(closing thread due to thumbs up)
I mostly think this invites bike-shedding, because it is less clear where to draw the line without knowing any of the imaginary future plans. E.g. should network time be the same alias like p2p time, and mempool time, and validation time, or should even different fields in p2p have different named time aliases, ...? [Meta note: Generally it is best to provide each review topic in a new review thread, and not in the global thread. Otherwise, it is harder to follow the global thread, because it mixes different sub-threads]
I agree with @maflcko, and see similar things with other aliases that were introduced in the codebase. I think they are a poor tool for being the impetus for more in depth code changes. Sometimes they can help documenting intent, but for the reasons named here I don't think they really make it easier.
🐙 This pull request conflicts with the target branch and needs rebase.
Thanks for the replies. To be clear my only objection to this PR is the expanded use of the
NodeClock::epochconstant which I think will lead to bugs and encourage writing bad code. I suggested various specific alternatives in my comments, and also ACKed this PR so these comments can be ignored.My suggestion to use type aliases instead of hardcoding
NodeClock::time_pointis less important, because usingNodeClock::time_pointis definitely better than what current code does, so type aliases would just be an additional improvement. I did list specific reasons I think they are a good idea (making intent clearer by indicating which times need to have the same types and which time do not, making it possible to introduce module-specfic validation and serialization formats without needing to update many call sites) while objections seem more shallow and hand-wavy ("invites bike-shedding", "they are a poor tool") that list no technical downsides. Seems fine to agree to disagree on this, though.re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3507087415
I don't know what happened here, but I'm definitely not asking you to remove refactoring label, or add casts to seconds.
Quoting my original comment "Can commit message be clarified" "commit message should clarify" and "Changing behavior should be ok and probably even an improvement"... and I'm just saying commit messages in this PR would be better if they stated which commits change behavior of the code and which do not.
A concrete reason for asking this is that while you and I have changed
time_pointcode recently and are familiar with these edge-case behavior changes, other reviewers and readers may not be. If a commit only says it is a refactor and swaps out C++ types, reviewers might not know they should be looking out for these cases.re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3506795156
I think I'm not sure what you are asking here. I have acked this PR. I just think this commit (fa1a22927adac877c46645b586ecda8ae1592002) is bad and unnecessary and suggested several alternatives that would be better:
std::optional,time_point::minortime_point::maxvalues depending on the situation).NodeClock::epochconstant by using the standard C++ approach of calling the defaulttime_point{}constructor.NODE_UNSET_TIMEconstant to make it clear that a magic value is being used that needs to be checked for separately, and also discourage code in the style from being written in the future.Sorry, I don't follow here. Using
epochorminis equally irrelevant and wrong here: The value isn't used and trying to imply that a timeout will happen in the past is confusing. Either this should be left as-is (which I've done in this pull request), or this should be rewritten from the ground up, but I think this pull is already large enough. Unless reviewers want me to rewrite this in a separate commit, I'll leave this as-is.Thx done (in a new commit), and resolving thread
thx, done, and resolving
thx, done, and resolving
Thx, done. Also used
::minhere over::epoch. Also, resolving thread.thx, done
Thx, done in the commit msg and docstring.
Thx for the review. Addressed/replied to all review threads while force pushing the rebase. The second-to-last commit was split up and rewritten from scratch.
Ok, I went ahead and pushed a commit to use nullopt instead. The commit is separate, so that it explains why the change is correct and why epoch-zero or min (or any other value) is irrelevant.
Code review ACK fa314e433020667d1b1171b10083b5a53964d0f2. IMO, this is much improved since the last version, and the last version was already a nice cleanup, so thanks for the updates! I still need to look over the latest review comments, but I reviewed all the code and left a few suggestions. Again feel free to ignore them.
In commit "refactor: Allow NodeClock::epoch to be used in NodeSeconds context" (fa815059fc1a4eabbd81d586b8e515315eba5ec3)
I need to catch up on your latest comments so sorry if this is explained somewhere, but I still do not understand the reasons behind the choice to prefer
NodeClock::epochoverNodeSeconds{0s}and definitely think it would be good to explain why you think using theepochconstant is better in the commit message.I think using the epoch constant is bad because:
epochconstant so it harder to remove the constant. The presence of this constant is bad because it encourages broken, nonstandard code to be written, as I think we both agree.IMO the PR would be improved dropping the code changes in this commit (I do think the comment added here is helpful).
In commit "refactor: Use std::optionalNodeClock::time_point instead of std::chrono::microseconds for m_headers_sync_timeout" (fae47ceffe929bc83647174f9b4cc52814c9b55d)
Also seems like logic this commit would be simpler if it used
maxinstead of std::optionalIn commit "refactor: Use std::optionalNodeClock::time_point instead of std::chrono::microseconds in net_processing" (facb9ef75ef9c8e264ba1238f864df5627493d13)
Seems like logic for most of these variables would be simplified using min/max constants instead of optional. Like m_stalling_since would be simpler using max as its unset value, m_next_inv_send_time and m_next_local_addr_send would be simpler using min
In commit "refactor: Use NodeSeconds for m_best_block_time" (fa3d651b11a008ad6712824776e131b9510f4666)
I'm surprised this is using the default constructor instead of setting NodeClock::epoch. I do think using default constructor is better than using epoch. But using std::optional here would seem better than either. Right now ApproximateBestBlockDepth returns a huge nonsense value when this is 0, but it would be better if ApproximateBestBlockDepth returned std::optional as well.
Note: Some commits are still changing behavior without being labeled. For example in fa4e8efbb8b2e3f6460683ee6e1b3aaa3a662d3e logic deciding which peers to evict was based on seconds, now it is based on nanoseconds or whatever precision system_clock uses, which is a minor improvement, but also a potentially observable change.
IMO, it would be better if commits explicitly said "This commit is not changing any changing behavior" "This commit is changing behavior slightly..." so intent behind the changes would be clear.
Closing thread for now, looks like there is a new thread on the same commit/topic: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3548400943
Closing thread for now. Continued thread for same commit/topic is https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3548378616
Resolving thread for now. A new thread seems to have been started about
m_headers_sync_timeoutin https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3548321570Why are you surprised that I literally addressed your review feedback? https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3491970807 says:
It is not allowed to call
ApproximateBestBlockDepthwhen the value is not set. Also, there is no code path where it is not set. I don't think it makes sense to bubble up errors that can never happen. In any case, I am not changing any behavior in this commit, so changingApproximateBestBlockDepthseems out of scope.I am not sure what the best way is to catch errors that can never happen here. Historically, in C++17, one could use uninitialized memory for atomic durations. However, in C++20, this is no longer possible after https://wg21.link/p0883r2. In any case, it was never possible with time_points, because they have a user-provided ctor. See also https://godbolt.org/z/a73hvs8rr
I am confident that everyone knows that epoch == zero == default ctor. If they don't, it would be faster to look it up, than it takes me to write this comment.
No, the intent is not clearer, and zero is not arbitrary here. zero is embedded into the code and into the serialization format. Idk, I'd prefer to leave this as-is, but I can introduce an
ADDRMAN_MAGIC_ZERO = NodeSeconds{0s}; // used for internal corruption checks.No, the docstring says that a magic zero should not be used, so the presence of the constant discourages use of the magic zero. Also, it is not harder to remove the constant: It is a 3-line scripted diff before and after the changes here to remove it, if anyone wanted to do that.
Sure, modified the commit messages a bit.
Thx, done
Sure, done.
Thx for the review, replied to all threads and force pushed.
🚧 At least one of the CI tasks failed.
Task
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/29028565223/job/86154858915LLM reason (✨ experimental): CI failed due to a C++ build error:
net_processing.cppfails to compile becausecurrent_timeis an undeclared identifier (clanguse of undeclared identifier).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.
Approach ACK for improved type safety in time handling, this makes the code easier to read and harder to make mistakes.
I think the
epochapproach is sensible, as it is now documented that it should not be used in new code, and I personally find that (with the docstring) it makes things more clear (as someone not super familiar with p2p).meta-nit: I think the current commit structure is reasonable, but I would have preferred having separate commits for refactoring changes (i.e. changing the type) and for behaviour changes (i.e. changing the default, using min/max etc). Not a blocker, it's doable as-is, but it would speed the (re-)review cycle up for me.
meta-nit: faba25132928b8bdce526957d3b311fca3e75faf should not have
refactorin its title. This new behaviour looks benign to me too, but I think we should highlight that it has behaviour change.Thanks for the approach review! I've:
Use time_point::min() over epoch-zero for m_last_block_announcement. This pull is meant to be a refactor.Code review ACK fa146ffed41a5355d1374b4c4f912f3701e0beec. Nice improvement using the time point type to represent times, instead of duration types or integers.
Unfortunately, it looks like uses of the
epochconstant are still increasing from10to26in this pull, but this is better than the44uses in previous versions.I left some new suggestions, but as always feel free to ignore them. Thanks for all the updates!
re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3549460422
I'm not sure how they would know that.
epochis a formerly undocumented, nonstandard constant that is set in one clock type but not others. And even though people can figure outepochmeans 0, It is much more obvious that 0 means 0.Again using 0 to represent 0 would be recommended.
Yeah we are talking past each other here. If 0 needs to be used, a literal 0 is a good way to represent it because it looks like a magic value and is a magic value.
Fortunately 0 does not need to be used most places, and new code should avoid using it by using min/max/optional instead. The one exception might be serialization code, but in that case the 0 can be written in the serialization logic and does not need to affect the way times are represented in memory.
An
epochconstant makes bad code look less bad and encourages more code based on it to be written. More uses of the constant also make the constant harder to remove, even with a scripted diff.Suggestion: Obviously my preferred alternative would be to use
0instead ofepochin the code, but I at least think you should update the commit to contain some positive explanation of why you think the constant is good to use, not just say it "should be allowed" and "Code may reference this constant." When you are allowing the constant to be used more places, and using it more places, it seems like you should be able to describe what motivated you to do these things.re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3549457200
Yes I was surprised you took the suggestion here and nowhere else.
Thanks, I didn't realize there was no code path where
m_best_block_timecould be read before it is set. When I made my comment I was assuming that is was intended forApproximateBestBlockDepthto return a really large value in this case soNETWORK_LIMITEDwould not be used.Suggestion: The fact that
m_best_block_timedoes always get set to a different value is not obvious, and I think there should at least be a comment here like "// default value is never used" to be clear that it's a bug if this value does get used.I also think it could be safer to make this field
std::optionaland assert that it is set before it's used, but absent that, just having a comment would be helpful for making this not look like it is trying to return garbage.In commit "refactor: Use NodeClock::time_point instead of std::chrono::microseconds in net_processing" (cccc523550951e5c4b0d635a5462851ff22c6806)
Could mention this field in commit message
In commit "p2p: Use NodeClock::time_point for m_last_block_announcement" (fa6f2e992785b88670a9c6d78078fc73c866e02e)
Not important, but this is also dropping
\n, and I think it's good for commit messages to note when they make unrelated changes, so it's clear they are intentional. There is also another\nkept immediately below.re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3542813639
Yes, it wasn't obvious the value was ignored and is gated on
fSyncStarted.It looked like the code was trying to represent 3 states: not syncing, syncing, and done syncing, but
fSyncStartedmeans the first state is never actually checked.Next question might be why there is an
fSyncStartedvariable instead of usingstd::optional, but in any case use ofminis probably not advisable here.In commit "refactor: Allow NodeClock::epoch to be used in NodeSeconds context" (fa3ed0cf09322553bb2f94e76744d1dd8081ea70)
This seems like bad advice and the previous comment in fa815059fc1a4eabbd81d586b8e515315eba5ec3 was better. The problem is:
An unset variable should not be represented as zero. That is a footgun and a cause of bugs. If you think there are cases where this is appropriate I'd like to know what they are, and this comment should be specific about what they are.
Log messages and RPCs should not be using this constant if they want to display or return zero when literal zeroes would be clearer. Also they are probably better off writing "unset" or
nullthan using zeroes at all. C++ code is better off usingstd::optional, or min/max times when the goal is to represent the last time something happened, or the next time it should happen.I still believe that
epochis a non-standard, error-prone constant should be removed entirely. Zeroes are not a good way represent unset times. In cases where they can't be avoided, literal zeros can be used and would preferable for transparency, and to make intent clear because the internal clock epoch time should not be relevant to application logic. Alternately, if there is some reason we don't want to write zeroes literally, we could introduce a constant likeNODE_UNSET_TIMEwhich would also express intent more clearly and also make bad code stand out.Suggestion would be to drop this commit (preferred) or to improve the comment. I think earlier suggested comment could fit well here.
I don't disagree, but this pull request is already too large, and this commit is a pure refactor (after compilation the asm will likely be identical before and after this commit), so I don't want to jam in more unrelated fixups.
Also, peerman isn't even used before connman is started, so simply constructing peerman with the correct value avoids the use of optional (and comment), but again, this pull is already too large to add more changes to it.
Looks like a third thread was started to bike-shed the color of zero. Closing this one for now, and let's move discussion there: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3595379854
I think all other reviewers prefer the constant, so I won't be dropping it. I can add the words
Old code ...andNew code ..., or some other wording, if I have to re-touch.About the RPC/logs: Yes it is possible to change
to
or to
, but this would have to be separate commit and this pull is already too large to include that here.
Also, breaking behavior changes like switching
0tonullor"unset"in RPC are not allowed in this refactor-only PR.I am happy to review a later pull, if someone creates one.
The
\nis not needed by the logger. May adjust the commit message if I have to re-touch.May adjust the commit message if I have to re-touch.
Reviewed fa146ffed41a5355d1374b4c4f912f3701e0beec
Code LGTM but want to give it another review round to double check potential behaviour change. Left a few comments, but no blockers.
I find relying on sentinels (
if (State(staller)->m_stalling_since == NodeClock::time_point::max())) to be an antipattern, and would have found it more clear if this were astd::optional.git diff on fa146ffed4
Generally, I think
::min()and::max()are natural choices when we can use them without relying on them as sentinel values. Once that no longer holds, I thinkstd::optionalis more clear.git diff on fa146ffed4
Not a blocker, I don't want these style preferences to get in the way of the real improvements.
in fa3c6bae01bdf472404612d492c81219f6c4f796:
orthogonal, but while touching, would be good to use
TicksSecondshere to guard against errors whenm_best_block_timechanges its duration type?git diff on fa3c6bae01
nit: "maintain" would now require nanoseconds. No practical implications either way, but might be slightly less confusion to not have a different duration here?
re: https://github.com/bitcoin/bitcoin/pull/35315#discussion_r3617453960
I haven't checked recently but last time I looked min and max were not used as sentinels, but meaningful values that make comparisons simpler and bugs harder to introduce.
If the claim is that types like
optionalorvariantshould be used whenever an individual value is checked for anywhere in the code, even when the value is meaningful, and even when using these types would complicate other comparisons, I'd question that claim. Not to say it's wrong, but just to say it should be judged on how it simplifies code or prevents bugs or has some concrete benefit in the specific situation. Not just that it's "more clear" or avoids an "antipattern".IMO needing to add
Assertsthat would otherwise be unnecessary, and write fragile comparisons likeif (!x || *x < y)andif (x && x < y)are reasons not to take this approach in this situation.Right,
optionalwas used in an earlier commit here (looks like GitHub purged facb9ef75ef9c8e264ba1238f864df5627493d13 already). The downsides were:if (!x || *x < y)orif (!x || x < y)orif (x<y). I mean, handling the nullopt sentinel value specifically seems clearer, but the compiler/stdlib doesn't enforce that, so maybe just useif (x<y)? But then, one may as well use::min()/::max()as equally good sentinel value without the code and logic overhead from optional?value()on nullopt will throw. Sure, those are indications of software bugs, but in P2P code we seem to be usingAssumeinstead ofAssert. See for example theAssumeonm_next_inv_send_time. So instead of trying to avoid nullptr-crash or a throw with optional and somehow still getAssumesemanticts (crash in Debug build, fallback in Release), one might as well just use::min()/::max()as perfectly fine sentinel values that supportAssumewithout a risk of crash/throw.epochas sentinel value, similar to::min(). Bitcoin Core doesn't really allow times at epoch, or before, so epoch-zero and::min()are equivalent sentinel values.::max().I mean this is pretty pointless, the base timeout is 15 minutes and the per-header timeout-diff is 1ms, so even with a 1 week-old best header, we are bike-shedding about 15min1.008sec vs 15min1.007sec.
My preference would be to just remove this useless "precision" code, or use
SecondsDoublefor "precision".edit: Miners can (and do?) "wiggle" the time here by more than one pow-target-spacing anyway, so implying a greater precision here seems confusing?
Thx, done, but with a different patch
thx, changed commit msg
thx, changed commit msg
Thx, minimally improved docstring.
I agree, it seems unnecessary and confusing.
That's fair. In the case of
m_next_inv_send_time, I think using::min()to indicate that we should send an inv asap, or::max()that we shouldn't send one is natural and clear and doesn't assign any special meaning to::min()or::max(). InInitiateTxBroadcastToAll, however,::min()does now not just guarantee that we're definitely at some later point, it also adds the additional meaning that a version handshake has not yet been completed. That has absolutely nothing to do with time. The reader now has to be aware of all the usage of the variable, and/or it has to be completely documented.When
m_next_inv_send_timeisstd::optional, the type makes it perfectly clear that there is a discontinuity to be aware of. That's why I think it's more clear.Now, probably the most proper solution would be to just stop using
m_next_inv_send_timeas a proxy for a completed version handshake, but I haven't looked into how feasible that is here.For other variables, like
m_stalling_since, I think it is better to have a sensible (std::nullopt) vs a nonsensical (::max(): a "since" in the future can never make sense) value.My diff added 2
Asserts that could equally well be omitted, but they're just making the invariant explicit whereas the current code implicitly assumes them. I think explicit is better.It's more verbose (which can be improved with
value_or(), but I'm not sure fragile is the appropriate term for making the discontinuity/semantic overload more explicit?Perhaps it's not suitable for the p2p code, but we could still adopt patterns like
Assume(some_var).value_or(::min())? It's more verbose, but I think it is helpful to be more explicit?I agree we can't enforce clean code here, but with
std::optionalwe can at least allow it.I agree it's not worse than
epoch.I agree, I think
::max()for a timeout is very natural, even when it has not explicitly been set.Not sure what to do here. This pull is already 10 commits, and switching to optional with
AssertorAssume(some_var).value_or(::min()/max())feels like it is going to explode the review scope here.I'd say the review scope here should restrict itself to compile-time type-changes only (modulo precision changes).
changing a few sentinel values from epoch-zero to min/max seems fine, but if reviewers can't agree on them for now, it seems best to postpone the two commits (
fa8a149c29&fa58d8f4fb) and just fully restore the initial (and reviewed) version of this pull request (https://github.com/bitcoin/bitcoin/pull/35315#issuecomment-4990553024)I'm happy to keep it as-is, it's not a regression vs master and the PR has too many other benefits to be spending too much time/energy on this rather small issue. I just wanted to share my view that I think we should ideally have less
::min()::max()sentinels, not more.ACK
fab4bd7f2bWould be useful to document all sentinels:
git diff on
fab4bd7f2bnit: any reason we use
Node<NodeSeconds>()here instead ofNodeClock::now()?🐙 This pull request conflicts with the target branch and needs rebase.
Code review ACK
fab4bd7f2b. Changes since last review: tweakingepochcomment and commit message as suggested, replacing nPowTargetSpacing with PowTargetSpacing a few places, simplifying HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER calculation making it slightly less precise but off by 1ms at mosttACK
fab4bd7f2bBuilt and ran the unit suites and the p2p functional tests.
Left 3 nits (feel free to ignore)
nit: the rest of the file moved to
consensusParams.PowTargetSpacing(), and this is the last duration still built by hand fromnPowTargetSpacing.nit:
MaybeSendAddr,GetRequestsToSendandMaybeSendFeefilterall end up taking thenowfrom the top ofSendMessages, andConsiderEvictionis the one that still takes its own read. Worth passingnowhere too?nit: the eviction commit says the precision makes
SelectNodeToEvictmore precise throughCompareNodeBlockTimeandCompareNodeTXTime, and this fixture still hands it whole seconds. Casting both times back to seconds insideSelectNodeToEvictleavespeer_eviction_testgreen, and with these initialisations in milliseconds it fails. The other five in this test take the same change.The announcement comparison in
EvictExtraOutboundPeershas the same gap, worth one there too?Base:
4303f3b7f0775cdbbe77faddf142e1e44fa590caHead:
fab4bd7f2bf8eb78efff00a6d1abcb28187e0063No verified findings are available from this review.
Review coverage was incomplete.
Review limitations
Full review report
Ping for rebase @maflcko