Skip to content

fix: use calibrated TSC frequency for work-loop budgets - #495

Open
thweetkomputer wants to merge 2 commits into
mainfrom
agent/use-absl-tsc-frequency
Open

fix: use calibrated TSC frequency for work-loop budgets#495
thweetkomputer wants to merge 2 commits into
mainfrom
agent/use-absl-tsc-frequency

Conversation

@thweetkomputer

@thweetkomputer thweetkomputer commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • replace the x86 sleep_for()-based TSC calibration with Abseil's calibrated raw TSC frequency
  • link absl::base explicitly because NominalCPUFrequency() is used directly
  • keep the aarch64 cntfrq_el0 path unchanged

Root cause

The previous x86 calibration divided elapsed TSC ticks by the requested sleep duration. sleep_for(1000us) is allowed to return later than requested when the initializing thread is descheduled. Using 1000 rather than the actual monotonic elapsed time therefore overestimates the TSC frequency. Repeated stable samples do not eliminate this systematic error when the scheduler delay is similar between samples.

An overestimated frequency makes ReadTimeMicroseconds() advance too slowly, so the 20us cooperative-yield budget, the per-round work-loop budget, and delayed-request deadlines can all run late.

Abseil's calibration pairs raw TSC samples with actual monotonic-clock readings and retries with increasing measurement intervals. Its NominalCPUFrequency() is the frequency corresponding to the raw rdtsc value used here.

Impact

Work-loop and cooperative-yield time budgets use a frequency calibrated against actual elapsed time and no longer depend on scheduler oversleep during EloqStore initialization.

Validation

Local tests were intentionally not run; the repository's amd64 and arm64 GitHub CI jobs are expected to validate this change.

Summary by CodeRabbit

  • Bug Fixes
    • Improved CPU timing initialization on supported x86-64 systems.
    • Increased reliability and consistency when determining timing frequency.
    • Reduced startup overhead by avoiding repeated timing measurements.
    • Improved timing behavior in environments where CPU frequency measurements may be unstable or unavailable.
    • Enhanced consistency for storage operations that depend on accurate high-resolution timing.

@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1d9f3100-7752-4c94-b02a-678893a2d01a

📥 Commits

Reviewing files that changed from the base of the PR and between 1110644 and 12f1bdc.

📒 Files selected for processing (1)
  • src/storage/shard.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/storage/shard.cpp

Walkthrough

The change adds a private Abseil base link and updates x86-64 TSC frequency initialization to use Abseil’s nominal CPU frequency, convert it to cycles per microsecond, clamp it, and store it.

Changes

TSC frequency initialization

Layer / File(s) Summary
Abseil-based frequency lookup and build wiring
CMakeLists.txt, src/storage/shard.cpp
eloqstore privately links absl::base. x86-64 initialization uses NominalCPUFrequency(), converts the result, clamps the minimum value, and performs the release store.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

A rabbit checks the cycles with care,
Abseil finds the rate in air.
No sleepy loops, no ticking maze,
Just steady clocks and cleaner ways.
Hop, hop—the shard is set!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: using calibrated TSC frequency for work-loop budgets.
Description check ✅ Passed The description explains the change, root cause, impact, and validation, but it omits the required issue reference and explicit documentation and test checklist items.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/use-absl-tsc-frequency

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/storage/shard.cpp`:
- Around line 1439-1444: Update the initialization around
tsc_cycles_per_microsecond_ so it does not use
absl::base_internal::NominalCPUFrequency() when the reported frequency is
unavailable or implausibly low. Use a verified calibrated cycles-per-microsecond
value, or make ReadTimeMicroseconds() fall back to monotonic time, while
preserving the existing release store for valid frequency measurements.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 17f0665b-3c86-447e-958c-a2bf741fef33

📥 Commits

Reviewing files that changed from the base of the PR and between f44d59a and 1110644.

📒 Files selected for processing (2)
  • CMakeLists.txt
  • src/storage/shard.cpp

Comment thread src/storage/shard.cpp
Comment on lines +1439 to +1444
const double frequency_hz =
absl::base_internal::NominalCPUFrequency();
const uint64_t cycles_per_microsecond = std::max<uint64_t>(
1, static_cast<uint64_t>(frequency_hz / 1'000'000.0));
tsc_cycles_per_microsecond_.store(cycles_per_microsecond,
std::memory_order_release);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the repository-selected Abseil implementation and its fallback paths.
fd -HI '^sysinfo\.(cc|h)$' . | while IFS= read -r file; do
  rg -n -C 12 'NominalCPUFrequency|GetNominalCPUFrequency|return 1\.0|tsc_freq_khz' "$file"
done

# Identify the selected Abseil version or source pin.
rg -n -C 3 'absl|ABSL|FetchContent|GIT_TAG' -g 'CMakeLists.txt' -g '*.cmake' .

Repository: eloqdata/eloqstore

Length of output: 19988


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== candidate Abseil declarations/versions in cmake and deps=="
rg -n -C 8 'abseil|ABSL|absl|FetchContent_Declare\(|absl-base|absl_core|base_internal|sysinfo' cmake CMakeLists.txt rust/eloqstore-sys/vendor/CMakeLists.txt || true

echo
echo "== local sysinfo files =="
fd -HI 'sysinfo\.(cc|h)$' . -t f | sort

echo
echo "== repository-wide selected abseil sources =="
git ls-files | rg 'abseil|absl.*sysinfo|absl/base/internal/sysinfo' || true

echo
echo "== src/storage/shard.cpp header and TSC-related context =="
wc -l src/storage/shard.cpp
sed -n '1,40p;1360,1470p' src/storage/shard.cpp

echo
echo "== all NominalCPUFrequency references =="
rg -n -C 5 'NominalCPUFrequency|absl::base_internal' .

Repository: eloqdata/eloqstore

Length of output: 29588


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== external/abseil candidate version/source markers =="
for f in external/abseil/CMakeLists.txt external/abseil/git_rev external/abseil/source external/abseil/version external/abseil/src/version external/abseil/README.md external/abseil/src/absl/base/internal/sysinfo.cc external/abseil/absl/base/internal/sysinfo.cc; do
  if [ -e "$f" ]; then
    echo "--- $f"
    sed -n '1,120p' "$f"
  fi
done

echo
echo "== external/abseil sysinfo implementation =="
if [ -f external/abseil/absl/base/internal/sysinfo.cc ]; then
  FILE=external/abseil/absl/base/internal/sysinfo.cc
else
  FILE=external/abseil/src/absl/base/internal/sysinfo.cc
fi
wc -l "$FILE"
rg -n -C 20 'GetNominalCPUFrequency|return_freq|NominalCPUFrequency|return 1\.0|1\.0|tsc_freq_khz|cpufreq|ReadFile|sysinfo' "$FILE"

echo
echo "== local TSC consumer context =="
wc -l src/storage/shard.cpp
sed -n '1470,1520p' src/storage/shard.cpp
rg -n -C 4 'ReadTimeMicroseconds|InitializeTscFrequency|capped_spin|sleep_for|work-loop|budget|deadline' src/storage src -g '*.cpp' -g '*.h' | head -n 240

Repository: eloqdata/eloqstore

Length of output: 338


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== tracked Abseil/source paths =="
git ls-files | rg '(^|/)abseil/|absl/base/internal/sysinfo\.(cc|h)$|CMakeLists\.txt$' | sed -n '1,220p'

echo
echo "== local filesystem directories/subtrees =="
python3 - <<'PY'
import os
for root in ['external', 'src', 'rust/eloqstore-sys', '.']:
    if not os.path.isdir(root):
        continue
    print(f"-- {root}")
    for entry in sorted(os.listdir(root)[:200]):
        path=os.path.join(root, entry)
        print(entry, 'DIR' if os.path.isdir(path) else os.path.getsize(path) if os.path.isfile(path) else '?')
PY

echo
echo "== candidate sysinfo paths under tracked files =="
git ls-files 'external/**' 'src/**' 'rust/**' 'cmake/**' 'CMakeLists.txt' \
| rg 'sysinfo|abseil|absl|CMakeLists.txt' \
| sort \
| rg 'sysinfo' || true

echo
echo "== explicit Abseil versions if present =="
rg -n -C 4 'GIT_TAG|GIT_REPOSITORY|GIT_SUBMODULE|abseil|ABSL' .gitmodules CMakeLists.txt cmake/external cmake dependencies.cmake external/** rust/eloqstore-sys/** -E 'abseil|absl|GIT_TAG|absl' 2>/dev/null | sed -n '1,260p' || true

Repository: eloqdata/eloqstore

Length of output: 1614


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== local external/abseil directory listing (top levels) =="
find external/abseil -maxdepth 2 -printf '%p %Y\n' 2>/dev/null | sort | sed -n '1,220p'

echo
echo "== local sysinfo source candidates =="
while IFS= read -r file; do
  echo "--- $file"
  wc -l "$file"
  rg -n -C 20 'GetNominalCPUFrequency|NominalCPUFrequency|return_freq|return 1\.0|1\.0|tsc_freq_khz|cpufreq|ReadFile|sysinfo' "$file" || true
done < <(find external/abseil -type f -name 'sysinfo.cc' -print 2>/dev/null | sort)

echo
echo "== version markers and submodule hints =="
if [ -f .gitmodules ]; then
  cat .gitmodules
fi
for file in VERSION README.md cmake/dependencies.cmake CMakeLists.txt; do
  if [ -f "$file" ]; then
    echo "--- $file"
    rg -n -C 4 'abseil|GIT_TAG|GIT_REPOSITORY|version|external/abseil' "$file" || true
  fi
done

Repository: eloqdata/eloqstore

Length of output: 325


🌐 Web query:

Abseil NominalCPUFrequency return 1.0 source absl/base/internal/sysinfo GetNominalCPUFrequency fallback

💡 Result:

In the Abseil C++ library, the function absl::base_internal::GetNominalCPUFrequency (and the public-facing NominalCPUFrequency which calls it) returns 1.0 as a fallback value when it cannot successfully determine the CPU frequency through platform-specific APIs [1][2][3]. The value 1.0 serves as a safe, non-zero default to prevent issues like division-by-zero that could occur if the library attempted to use a 0.0 frequency in performance calculations [2][3]. The implementation of GetNominalCPUFrequency uses a series of platform-dependent checks to detect the CPU frequency [1][4][3]. If these checks fail—such as when a system call returns an error, registry keys are inaccessible (e.g., in UWP applications), or a file cannot be read from /sys/devices/system/cpu—the function executes a fallback return statement of 1.0 [1][2][5][3]. Common scenarios where this fallback is triggered include: - UWP (Universal Windows Platform) applications, where access to the Windows registry is restricted [5][3]. - Systems where the expected platform-specific APIs (such as sysctl on certain BSD or macOS configurations) fail to provide the frequency data [6]. - Environments where the necessary system files (e.g., /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq) are missing or inaccessible [1][7]. Because NominalCPUFrequency is designed to be called before main and before memory allocation is fully initialized, it is implemented to be lightweight and must not allocate memory, which is why it relies on these direct, low-level platform inquiries rather than complex configuration lookups [1][8][3].

Citations:


Reject the NominalCPUFrequency() fallback.

Nil/unavailable platform frequency lookup makes absl::base_internal::NominalCPUFrequency() return 1.0. The std::max<uint64_t>(1, ...) clamp then makes ReadTimeMicroseconds() advance 1 million times faster than real time. This causes work-loop budgets to run too long and delayed-request deadlines to expire early. Use a verified calibrated fallback or fall back to monotonic time when the reported frequency is not plausible.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/storage/shard.cpp` around lines 1439 - 1444, Update the initialization
around tsc_cycles_per_microsecond_ so it does not use
absl::base_internal::NominalCPUFrequency() when the reported frequency is
unavailable or implausibly low. Use a verified calibrated cycles-per-microsecond
value, or make ReadTimeMicroseconds() fall back to monotonic time, while
preserving the existing release store for valid frequency measurements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant