← Back to Pull requests

feat(versiondb): add compact-versiondb command with rate limit #138

Merged
JayT106 merged 10 files (517 lines) on Oct 23, 2026 16:17 UTC
View on GitHub
JayT106 JayT106 commented on Oct 09, 2026 16:17 UTC
Author

What

Adds changeset compact-versiondb <versiondb-path> --rate-limit <MiB/s>. It's an offline full compaction that rewrites every versiondb SST file with the current compression (ZSTD with a dictionary at the bottommost level).

Also removes the memiavl test TestMultiTreeWriteSnapshotConcurrentCancellation. It was flaky (a 5 ms sleep raced the write), and once made deterministic it duplicated the existing cancel-before-start tests.

Issue

ingest-versiondb-sst leaves LZ4 files and restore-versiondb leaves uncompressed ones. #137 fixes this for new writes. Old files stay as they are until later writes overlap them, which may never happen. On the 2026-10-09 mainnet versiondb-pruned snapshot, 84% of 8.05 GB is uncompressed.

Solution

  • CompactRange with kForce. kForceOptimized isn't used because in RocksDB 10.x it can skip a bottommost file and still report success.

  • CompactRange returns no status. The command fails on background errors or if any pre-existing SST file is still live afterwards.

  • --rate-limit caps flush and compaction writes. The compaction can split into subcompactions, up to one per core.

  • The node must be stopped (RocksDB lock). Versioned history is kept.
  • On the mainnet snapshot: 8.05 → 3.58 GB (−56%) in 2m55s on a laptop SSD. This was measured before the switch to kForce, when some files may have been skipped, so treat it as approximate; kForce may also take longer.

    On the mainnet archive versiondb (height 101,209,380, 16-core arm64 VM, EBS gp3):

  • Size: SST files 144.1 → 129.2 GiB (−10.3%), whole dir 149.9 → 130.1 GiB (−13.2%, including a 5.3 GiB WAL flushed on open). 97% of the data was already ZSTD with a dictionary from the node's own TTL compactions, and those files rewrite at a 0.9985 ratio. The gain comes from 1.13B entries the compaction dropped (likely duplicate versions of the same key and timestamp) and from the LZ4 and uncompressed files.

  • Time: too slow for archive nodes. With the default max_background_jobs=2 the subcompactions get no threads, and a TTL compaction started at open blocks the manual one, so a full run is estimated at 1–1.5 days. With both fixed, it still took many hours: RocksDB keeps all versions of a user key in one job, and some keys have ~1–2B versions.

  • Correctness: cronosd v1.7.8 opens the compacted db, 216 historical queries at 9 heights return identical responses, and the node synced 380 mainnet blocks on it. A full key-and-version diff found no differences in the 23% of entries it covered before it was stopped.

  • Reads and commits are unchanged within noise.
  • Diff: 517 lines (+462 / -55) across 10 files Reviewer: thomas-nguy Review duration: 20160m
    All Vouch review confidence checks passed
    Residual risk 0.05 = Change Risk (0.54) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.54 · 517 lines diff across 10 files
    0.54
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.90 · 5 substantive comment(s)
    0.90
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    90%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.374
    Real PR Conversation Timeline
    20 items
    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 09, 2026 16:24 UTC
    Code Review
    versiondb/tsrocksdb/compact.go:1
    @@ -0,0 +1,73 @@
    +package tsrocksdb
    +
    +import (
    +	"errors"
    +	"fmt"
    +	"runtime"

    CodeQL / Sensitive package import

    Certain system packages contain functions which may be a possible source of non-determinism

    Show more details

    JayT106 JayT106 commented on code on Oct 09, 2026 16:39 UTC
    Code Review
    versiondb/tsrocksdb/compact.go:1
    @@ -0,0 +1,73 @@
    +package tsrocksdb
    +
    +import (
    +	"errors"
    +	"fmt"
    +	"runtime"

    Moved the runtime.NumCPU use into compactionDBOpts in opts.go, next to the existing IncreaseParallelism(runtime.NumCPU()), so compact.go no longer imports runtime (87956d3). It only sets thread counts in an offline CLI command, not consensus state.

    JayT106 JayT106 commented on Oct 09, 2026 17:13 UTC
    Author

    @claude review

    github-actions[bot] github-actions[bot] commented on Oct 09, 2026 17:13 UTC
    Bot

    Claude finished @JayT106's task in 1m 57s —— View job

    ---

    Review: feat(versiondb): add compact-versiondb command with rate limit

  • Read changed files

  • Review implementation quality and correctness

  • Post inline comments and summary
  • ---

    Summary

    The implementation is clean, well-scoped, and the test coverage is solid. A few issues worth addressing:

    Bugs / Correctness

    1. Ignored errors on GetIntProperty (compact.go:25, compact.go:33) — Both GetIntPropertyCF and GetIntProperty return (uint64, bool), but the booleans are silently discarded. The background-error check is the only failure signal for the compaction itself, so if GetIntProperty returns false (property name changed, column family mismatch, etc.) the function will return nil even when compaction failed, and before/after sizing will be wrong. See inline comments for suggested fixes.

    2. RateLimiter not destroyed (opts.go:81) — NewGenericRateLimiter returns a cgo-backed object that should be Destroy()-ed after the db closes. For a one-shot CLI command this is survivable (process exits), but worth documenting. Inline comment added.

    Minor

    3. Overflow guard comment (compact.go:21) — The math.MaxInt64>>20 guard is correct but non-obvious. A one-line comment would help. Inline comment added.

    4. Rate-limit test fragility (compact_test.go:139) — The 2 KiB/s throttle to enforce a ≥1s duration is sensible but depends on the write volume produced by the test fixtures. If that volume ever shrinks (e.g. fewer keys), the 1s bound could stop being meaningful without any test failure. A comment noting the expected write size would guard against silent regression.

    What's good

  • KForceOptimized is the right choice — avoids rewriting bottommost files twice.

  • Rate limiter plumbing (RateLimiterModeWritesOnly, refill period, fairness all match RocksDB defaults) looks correct.

  • compactionDBOpts correctly lives in opts.go alongside the existing IncreaseParallelism call (addressed in 87956d3).

  • Lock-release test in CompactVersionDBCmdSuite is a nice guard against handle leaks.

  • Empty-db path handled gracefully (returns 0 bytes, no error).

  • README example is accurate and includes the --rate-limit caveat.
  • github-actions[bot] github-actions[bot] commented on code on Oct 09, 2026 17:14 UTC
    Code Review
    versiondb/tsrocksdb/compact.go:1
    @@ -0,0 +1,38 @@
    +package tsrocksdb
    +
    +import (
    +	"fmt"
    +
    +	"github.com/linxGnu/grocksdb"
    +)
    +
    +// CompactVersionDB rewrites every sst file of the versiondb column family, bottommost level included,
    +// so all of them use the current compression, e.g. LZ4 or uncompressed files become ZSTD.
    +// The db must not be open in another process. rateBytesPerSec caps flush and compaction writes, 0 means unlimited.
    +func CompactVersionDB(dir string, rateBytesPerSec int64) (before, after uint64, err error) {
    +	if rateBytesPerSec < 0 {
    +		return 0, 0, fmt.Errorf("negative rate limit: %d", rateBytesPerSec)
    +	}
    +	db, cfHandle, err := openVersionDB(dir, compactionDBOpts(rateBytesPerSec))
    +	if err != nil {
    +		return 0, 0, fmt.Errorf("open versiondb: %w", err)
    +	}
    +	defer func() {
    +		cfHandle.Destroy()
    +		db.Close()
    +	}()
    +
    +	before, _ = db.GetIntPropertyCF("rocksdb.live-sst-files-size", cfHandle)

    The _ ignores the error from GetIntPropertyCF. If the property lookup fails (e.g. unknown property name typo), before will silently be 0, making the size comparison meaningless. Same issue on line 36 for after.

    Consider logging or returning the error, or at minimum asserting this won't fail in a test:

    	before, ok := db.GetIntPropertyCF("rocksdb.live-sst-files-size", cfHandle)
    	if !ok {
    		return 0, 0, fmt.Errorf("failed to read live-sst-files-size before compaction")
    	}
    

    github-actions[bot] github-actions[bot] commented on code on Oct 09, 2026 17:14 UTC
    Code Review
    versiondb/tsrocksdb/compact.go:1
    @@ -0,0 +1,38 @@
    +package tsrocksdb
    +
    +import (
    +	"fmt"
    +
    +	"github.com/linxGnu/grocksdb"
    +)
    +
    +// CompactVersionDB rewrites every sst file of the versiondb column family, bottommost level included,
    +// so all of them use the current compression, e.g. LZ4 or uncompressed files become ZSTD.
    +// The db must not be open in another process. rateBytesPerSec caps flush and compaction writes, 0 means unlimited.
    +func CompactVersionDB(dir string, rateBytesPerSec int64) (before, after uint64, err error) {
    +	if rateBytesPerSec < 0 {
    +		return 0, 0, fmt.Errorf("negative rate limit: %d", rateBytesPerSec)
    +	}
    +	db, cfHandle, err := openVersionDB(dir, compactionDBOpts(rateBytesPerSec))
    +	if err != nil {
    +		return 0, 0, fmt.Errorf("open versiondb: %w", err)
    +	}
    +	defer func() {
    +		cfHandle.Destroy()
    +		db.Close()
    +	}()
    +
    +	before, _ = db.GetIntPropertyCF("rocksdb.live-sst-files-size", cfHandle)
    +	compactOpts := grocksdb.NewCompactRangeOptions()
    +	defer compactOpts.Destroy()
    +	// skips the bottommost files this same compaction just wrote, instead of rewriting them twice
    +	compactOpts.SetBottommostLevelCompaction(grocksdb.KForceOptimized)
    +	db.CompactRangeCFOpt(cfHandle, grocksdb.Range{}, compactOpts)
    +
    +	// CompactRangeCFOpt returns no status, a failed compaction only shows up as a background error
    +	if bgErrors, _ := db.GetIntProperty("rocksdb.background-errors"); bgErrors > 0 {

    The _ here also ignores the error from GetIntProperty. Background errors are the only signal of compaction failure per the PR description, so a silent failure here would cause CompactVersionDB to return nil even when the compaction failed.

    	bgErrors, ok := db.GetIntProperty("rocksdb.background-errors")
    	if !ok || bgErrors > 0 {
    		return 0, 0, fmt.Errorf("compaction failed with %d background errors, see the rocksdb LOG file", bgErrors)
    	}
    

    github-actions[bot] github-actions[bot] commented on code on Oct 09, 2026 17:15 UTC
    Code Review
    versiondb/tsrocksdb/opts.go:1
    @@ -67,6 +71,18 @@ func OpenVersionDB(dir string) (*grocksdb.DB, *grocksdb.ColumnFamilyHandle, erro
     	return db, cfHandles[1], nil
     }
     
    +// compactionDBOpts caps flush and compaction writes at rateBytesPerSec (0 means unlimited) and lets a
    +// manual compaction use all cores, it otherwise runs on a single thread.
    +func compactionDBOpts(rateBytesPerSec int64) *grocksdb.Options {
    +	opts := grocksdb.NewDefaultOptions()
    +	opts.SetMaxSubcompactions(uint32(runtime.NumCPU()))
    +	if rateBytesPerSec > 0 {
    +		// refill period and fairness are rocksdb's defaults
    +		opts.SetRateLimiter(grocksdb.NewGenericRateLimiter(rateBytesPerSec, 100_000, 10, grocksdb.RateLimiterModeWritesOnly, false))

    The NewGenericRateLimiter call does not Destroy() the limiter object. The grocksdb.RateLimiter returned is a Go-wrapped C++ object; it should be destroyed after the db is closed to avoid a resource leak. Consider either:
    1. Storing it and deferring Destroy() in the caller's cleanup, or
    2. Accepting this as acceptable because the process terminates after compaction completes.

    If option 2, add a comment explaining the rationale so future readers don't add a spurious leak fix.

    github-actions[bot] github-actions[bot] commented on code on Oct 09, 2026 17:15 UTC
    Code Review
    versiondb/tsrocksdb/compact_test.go:1
    @@ -0,0 +1,176 @@
    +package tsrocksdb
    +
    +import (
    +	"encoding/binary"
    +	"fmt"
    +	"path/filepath"
    +	"testing"
    +	"time"
    +
    +	"github.com/linxGnu/grocksdb"
    +	"github.com/stretchr/testify/suite"
    +)
    +
    +const (
    +	historyKeys     = 200
    +	historyVersions = 4
    +)
    +
    +type CompactSuite struct {
    +	suite.Suite
    +}
    +
    +func TestCompactSuite(t *testing.T) {
    +	suite.Run(t, new(CompactSuite))
    +}
    +
    +func historyKey(i int) []byte {
    +	return fmt.Appendf(nil, "k%04d", i)
    +}
    +
    +// historyValue is nil for a key deleted at version 3, which is written again at version 4.
    +func historyValue(i, version int) []byte {
    +	if i == 0 && version == 3 {
    +		return nil
    +	}
    +	return fmt.Appendf(nil, `{"address":"0x%040x","balance":"%d","version":%d}`, i, i*1000+version, version)
    +}
    +
    +// writeHistory ingests the history as an LZ4 sst file, like build-versiondb-sst followed by ingest-versiondb-sst.
    +func (s *CompactSuite) writeHistory(dir string) {
    +	sstPath := filepath.Join(s.T().TempDir(), "history.sst")
    +	w := grocksdb.NewSSTFileWriter(grocksdb.NewDefaultEnvOptions(), NewVersionDBOpts(true))
    +	defer w.Destroy()
    +	s.Require().NoError(w.Open(sstPath))
    +	var ts [TimestampSize]byte
    +	for i := 0; i < historyKeys; i++ {
    +		key := prependStoreKey(testStoreKey, historyKey(i))
    +		// the sst writer needs the comparator order: newer version first
    +		for version := historyVersions; version >= 1; version-- {
    +			binary.LittleEndian.PutUint64(ts[:], uint64(version))
    +			if value := historyValue(i, version); value == nil {
    +				s.Require().NoError(w.DeleteWithTS(key, ts[:]))
    +			} else {
    +				s.Require().NoError(w.PutWithTS(key, ts[:], value))
    +			}
    +		}
    +	}
    +	s.Require().NoError(w.Finish())
    +
    +	store, err := NewStore(dir)
    +	s.Require().NoError(err)
    +	defer store.Close()
    +	s.Require().NoError(store.db.IngestExternalFileCF(store.cfHandle, []string{sstPath}, grocksdb.NewDefaultIngestExternalFileOptions()))
    +}
    +
    +func (s *CompactSuite) liveSSTFiles(dir string) map[string]struct{} {
    +	db, cfHandle, err := OpenVersionDBForReadOnly(dir, false)
    +	s.Require().NoError(err)
    +	defer NewStoreWithDB(db, cfHandle).Close()
    +
    +	files := make(map[string]struct{})
    +	for _, f := range db.GetLiveFilesMetaData() {
    +		if f.ColumnFamilyName == VersionDBCFName {
    +			files[f.Name] = struct{}{}
    +		}
    +	}
    +	return files
    +}
    +
    +func (s *CompactSuite) requireHistory(dir string) {
    +	store, err := NewStore(dir)
    +	s.Require().NoError(err)
    +	defer store.Close()
    +
    +	for i := 0; i < historyKeys; i++ {
    +		for version := 1; version <= historyVersions; version++ {
    +			v := int64(version)
    +			value, err := store.GetAtVersion(testStoreKey, historyKey(i), &v)
    +			s.Require().NoError(err)
    +			s.Require().Equal(historyValue(i, version), value, "key %d version %d", i, version)
    +		}
    +	}
    +}
    +
    +func (s *CompactSuite) TestCompactVersionDB() {
    +	testCases := []struct {
    +		name        string
    +		malleate    func(dir string)
    +		rateLimit   int64
    +		minDuration time.Duration
    +		expErrMsg   string
    +	}{
    +		{
    +			name:      "missing db",
    +			malleate:  func(string) {},
    +			expErrMsg: "does not exist",
    +		},
    +		{
    +			name:      "negative rate limit",
    +			malleate:  s.writeHistory,
    +			rateLimit: -1,
    +			expErrMsg: "negative rate limit",
    +		},
    +		{
    +			name: "db held by another handle",
    +			malleate: func(dir string) {
    +				store, err := NewStore(dir)
    +				s.Require().NoError(err)
    +				s.T().Cleanup(func() { store.Close() })
    +			},
    +			expErrMsg: "lock",
    +		},
    +		{
    +			name: "empty db",
    +			malleate: func(dir string) {
    +				store, err := NewStore(dir)
    +				s.Require().NoError(err)
    +				s.Require().NoError(store.Close())
    +			},
    +		},
    +		{
    +			name:     "history",
    +			malleate: s.writeHistory,
    +		},
    +		{
    +			// unthrottled the compaction takes milliseconds
    +			name:        "history with rate limit",
    +			malleate:    s.writeHistory,
    +			rateLimit:   2 << 10,

    2 KiB/s (2 << 10) is extremely low. With 200 keys × 4 versions and the JSON values used here, the total write volume is only a few hundred KB, so the 1-second minimum duration assertion should hold. But this is fragile: the test would pass even if the rate limiter were applied only to parts of the I/O path not exercised here. Worth documenting the expected write volume so future maintainers know when this bound is still meaningful.

    github-actions[bot] github-actions[bot] commented on code on Oct 09, 2026 17:15 UTC
    Code Review
    versiondb/client/compact.go:1
    @@ -0,0 +1,35 @@
    +package client
    +
    +import (
    +	"fmt"
    +	"math"
    +
    +	"github.com/crypto-org-chain/cronos-store/versiondb/tsrocksdb"
    +	"github.com/spf13/cobra"
    +)
    +
    +func CompactVersionDBCmd() *cobra.Command {
    +	cmd := &cobra.Command{
    +		Use:   "compact-versiondb versiondb-path",
    +		Short: "Recompress all versiondb sst files with the current compression options, the node must be stopped",
    +		Args:  cobra.ExactArgs(1),
    +		RunE: func(cmd *cobra.Command, args []string) error {
    +			rateLimit, err := cmd.Flags().GetUint64(flagRateLimit)
    +			if err != nil {
    +				return err
    +			}
    +			if rateLimit > math.MaxInt64>>20 {

    The overflow guard rateLimit > math.MaxInt64>>20 uses uint64 arithmetic for the comparison but the flag type is uint64, so values above math.MaxInt64 are representable. The check itself is correct, but the intent isn't obvious — consider a brief comment:

    // Prevent overflow when converting MiB/s to bytes/s for int64
    

    JayT106 JayT106 commented on code on Oct 09, 2026 17:18 UTC
    Code Review
    versiondb/tsrocksdb/compact.go:1
    @@ -0,0 +1,38 @@
    +package tsrocksdb
    +
    +import (
    +	"fmt"
    +
    +	"github.com/linxGnu/grocksdb"
    +)
    +
    +// CompactVersionDB rewrites every sst file of the versiondb column family, bottommost level included,
    +// so all of them use the current compression, e.g. LZ4 or uncompressed files become ZSTD.
    +// The db must not be open in another process. rateBytesPerSec caps flush and compaction writes, 0 means unlimited.
    +func CompactVersionDB(dir string, rateBytesPerSec int64) (before, after uint64, err error) {
    +	if rateBytesPerSec < 0 {
    +		return 0, 0, fmt.Errorf("negative rate limit: %d", rateBytesPerSec)
    +	}
    +	db, cfHandle, err := openVersionDB(dir, compactionDBOpts(rateBytesPerSec))
    +	if err != nil {
    +		return 0, 0, fmt.Errorf("open versiondb: %w", err)
    +	}
    +	defer func() {
    +		cfHandle.Destroy()
    +		db.Close()
    +	}()
    +
    +	before, _ = db.GetIntPropertyCF("rocksdb.live-sst-files-size", cfHandle)

    No change: before/after are only printed, so a failed size read shouldn't fail a compaction that succeeded. live-sst-files-size is a built-in property, and the history tests would still catch an unreadable before: it would read as 0 and the size-ratio assertion fails.

    JayT106 JayT106 commented on code on Oct 09, 2026 17:18 UTC
    Code Review
    versiondb/tsrocksdb/compact.go:1
    @@ -0,0 +1,38 @@
    +package tsrocksdb
    +
    +import (
    +	"fmt"
    +
    +	"github.com/linxGnu/grocksdb"
    +)
    +
    +// CompactVersionDB rewrites every sst file of the versiondb column family, bottommost level included,
    +// so all of them use the current compression, e.g. LZ4 or uncompressed files become ZSTD.
    +// The db must not be open in another process. rateBytesPerSec caps flush and compaction writes, 0 means unlimited.
    +func CompactVersionDB(dir string, rateBytesPerSec int64) (before, after uint64, err error) {
    +	if rateBytesPerSec < 0 {
    +		return 0, 0, fmt.Errorf("negative rate limit: %d", rateBytesPerSec)
    +	}
    +	db, cfHandle, err := openVersionDB(dir, compactionDBOpts(rateBytesPerSec))
    +	if err != nil {
    +		return 0, 0, fmt.Errorf("open versiondb: %w", err)
    +	}
    +	defer func() {
    +		cfHandle.Destroy()
    +		db.Close()
    +	}()
    +
    +	before, _ = db.GetIntPropertyCF("rocksdb.live-sst-files-size", cfHandle)
    +	compactOpts := grocksdb.NewCompactRangeOptions()
    +	defer compactOpts.Destroy()
    +	// skips the bottommost files this same compaction just wrote, instead of rewriting them twice
    +	compactOpts.SetBottommostLevelCompaction(grocksdb.KForceOptimized)
    +	db.CompactRangeCFOpt(cfHandle, grocksdb.Range{}, compactOpts)
    +
    +	// CompactRangeCFOpt returns no status, a failed compaction only shows up as a background error
    +	if bgErrors, _ := db.GetIntProperty("rocksdb.background-errors"); bgErrors > 0 {

    Done in f4ae395: an unreadable rocksdb.background-errors now returns an error instead of passing.

    JayT106 JayT106 commented on code on Oct 09, 2026 17:18 UTC
    Code Review
    versiondb/tsrocksdb/opts.go:1
    @@ -67,6 +71,18 @@ func OpenVersionDB(dir string) (*grocksdb.DB, *grocksdb.ColumnFamilyHandle, erro
     	return db, cfHandles[1], nil
     }
     
    +// compactionDBOpts caps flush and compaction writes at rateBytesPerSec (0 means unlimited) and lets a
    +// manual compaction use all cores, it otherwise runs on a single thread.
    +func compactionDBOpts(rateBytesPerSec int64) *grocksdb.Options {
    +	opts := grocksdb.NewDefaultOptions()
    +	opts.SetMaxSubcompactions(uint32(runtime.NumCPU()))
    +	if rateBytesPerSec > 0 {
    +		// refill period and fairness are rocksdb's defaults
    +		opts.SetRateLimiter(grocksdb.NewGenericRateLimiter(rateBytesPerSec, 100_000, 10, grocksdb.RateLimiterModeWritesOnly, false))

    grocksdb's SetRateLimiter takes ownership: it copies the shared_ptr and destroys the Go wrapper itself, so nothing leaks. Added a comment saying so (f4ae395).

    JayT106 JayT106 commented on code on Oct 09, 2026 17:18 UTC
    Code Review
    versiondb/tsrocksdb/compact_test.go:1
    @@ -0,0 +1,176 @@
    +package tsrocksdb
    +
    +import (
    +	"encoding/binary"
    +	"fmt"
    +	"path/filepath"
    +	"testing"
    +	"time"
    +
    +	"github.com/linxGnu/grocksdb"
    +	"github.com/stretchr/testify/suite"
    +)
    +
    +const (
    +	historyKeys     = 200
    +	historyVersions = 4
    +)
    +
    +type CompactSuite struct {
    +	suite.Suite
    +}
    +
    +func TestCompactSuite(t *testing.T) {
    +	suite.Run(t, new(CompactSuite))
    +}
    +
    +func historyKey(i int) []byte {
    +	return fmt.Appendf(nil, "k%04d", i)
    +}
    +
    +// historyValue is nil for a key deleted at version 3, which is written again at version 4.
    +func historyValue(i, version int) []byte {
    +	if i == 0 && version == 3 {
    +		return nil
    +	}
    +	return fmt.Appendf(nil, `{"address":"0x%040x","balance":"%d","version":%d}`, i, i*1000+version, version)
    +}
    +
    +// writeHistory ingests the history as an LZ4 sst file, like build-versiondb-sst followed by ingest-versiondb-sst.
    +func (s *CompactSuite) writeHistory(dir string) {
    +	sstPath := filepath.Join(s.T().TempDir(), "history.sst")
    +	w := grocksdb.NewSSTFileWriter(grocksdb.NewDefaultEnvOptions(), NewVersionDBOpts(true))
    +	defer w.Destroy()
    +	s.Require().NoError(w.Open(sstPath))
    +	var ts [TimestampSize]byte
    +	for i := 0; i < historyKeys; i++ {
    +		key := prependStoreKey(testStoreKey, historyKey(i))
    +		// the sst writer needs the comparator order: newer version first
    +		for version := historyVersions; version >= 1; version-- {
    +			binary.LittleEndian.PutUint64(ts[:], uint64(version))
    +			if value := historyValue(i, version); value == nil {
    +				s.Require().NoError(w.DeleteWithTS(key, ts[:]))
    +			} else {
    +				s.Require().NoError(w.PutWithTS(key, ts[:], value))
    +			}
    +		}
    +	}
    +	s.Require().NoError(w.Finish())
    +
    +	store, err := NewStore(dir)
    +	s.Require().NoError(err)
    +	defer store.Close()
    +	s.Require().NoError(store.db.IngestExternalFileCF(store.cfHandle, []string{sstPath}, grocksdb.NewDefaultIngestExternalFileOptions()))
    +}
    +
    +func (s *CompactSuite) liveSSTFiles(dir string) map[string]struct{} {
    +	db, cfHandle, err := OpenVersionDBForReadOnly(dir, false)
    +	s.Require().NoError(err)
    +	defer NewStoreWithDB(db, cfHandle).Close()
    +
    +	files := make(map[string]struct{})
    +	for _, f := range db.GetLiveFilesMetaData() {
    +		if f.ColumnFamilyName == VersionDBCFName {
    +			files[f.Name] = struct{}{}
    +		}
    +	}
    +	return files
    +}
    +
    +func (s *CompactSuite) requireHistory(dir string) {
    +	store, err := NewStore(dir)
    +	s.Require().NoError(err)
    +	defer store.Close()
    +
    +	for i := 0; i < historyKeys; i++ {
    +		for version := 1; version <= historyVersions; version++ {
    +			v := int64(version)
    +			value, err := store.GetAtVersion(testStoreKey, historyKey(i), &v)
    +			s.Require().NoError(err)
    +			s.Require().Equal(historyValue(i, version), value, "key %d version %d", i, version)
    +		}
    +	}
    +}
    +
    +func (s *CompactSuite) TestCompactVersionDB() {
    +	testCases := []struct {
    +		name        string
    +		malleate    func(dir string)
    +		rateLimit   int64
    +		minDuration time.Duration
    +		expErrMsg   string
    +	}{
    +		{
    +			name:      "missing db",
    +			malleate:  func(string) {},
    +			expErrMsg: "does not exist",
    +		},
    +		{
    +			name:      "negative rate limit",
    +			malleate:  s.writeHistory,
    +			rateLimit: -1,
    +			expErrMsg: "negative rate limit",
    +		},
    +		{
    +			name: "db held by another handle",
    +			malleate: func(dir string) {
    +				store, err := NewStore(dir)
    +				s.Require().NoError(err)
    +				s.T().Cleanup(func() { store.Close() })
    +			},
    +			expErrMsg: "lock",
    +		},
    +		{
    +			name: "empty db",
    +			malleate: func(dir string) {
    +				store, err := NewStore(dir)
    +				s.Require().NoError(err)
    +				s.Require().NoError(store.Close())
    +			},
    +		},
    +		{
    +			name:     "history",
    +			malleate: s.writeHistory,
    +		},
    +		{
    +			// unthrottled the compaction takes milliseconds
    +			name:        "history with rate limit",
    +			malleate:    s.writeHistory,
    +			rateLimit:   2 << 10,

    Commented the expected volume (f4ae395): the compaction writes ~4.5 KB, ~2 s at 2 KiB/s versus milliseconds unthrottled. If the volume shrank below ~2 KB the 1 s bound would fail, and disabling the limiter makes this case fail.

    JayT106 JayT106 commented on code on Oct 09, 2026 17:18 UTC
    Code Review
    versiondb/client/compact.go:1
    @@ -0,0 +1,35 @@
    +package client
    +
    +import (
    +	"fmt"
    +	"math"
    +
    +	"github.com/crypto-org-chain/cronos-store/versiondb/tsrocksdb"
    +	"github.com/spf13/cobra"
    +)
    +
    +func CompactVersionDBCmd() *cobra.Command {
    +	cmd := &cobra.Command{
    +		Use:   "compact-versiondb versiondb-path",
    +		Short: "Recompress all versiondb sst files with the current compression options, the node must be stopped",
    +		Args:  cobra.ExactArgs(1),
    +		RunE: func(cmd *cobra.Command, args []string) error {
    +			rateLimit, err := cmd.Flags().GetUint64(flagRateLimit)
    +			if err != nil {
    +				return err
    +			}
    +			if rateLimit > math.MaxInt64>>20 {

    Added the comment (f4ae395): MiB/s is converted to bytes/s, which must fit in an int64.

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 20, 2026 18:38 UTC
    Code Review
    versiondb/tsrocksdb/compact.go:1
    @@ -0,0 +1,68 @@
    +package tsrocksdb
    +
    +import (
    +	"errors"
    +	"fmt"
    +	"runtime"

    CodeQL / Sensitive package import

    Certain system packages contain functions which may be a possible source of non-determinism

    Show more details

    JayT106 JayT106 commented on code on Oct 20, 2026 18:43 UTC
    Code Review
    versiondb/tsrocksdb/compact.go:1
    @@ -0,0 +1,68 @@
    +package tsrocksdb
    +
    +import (
    +	"errors"
    +	"fmt"
    +	"runtime"

    No change: runtime.NumCPU only sets the compaction thread count in an offline CLI command, so it can't affect consensus. The alert is a note and the CodeQL check passes. Master already has the same alert open for opts.go (#36), where NewVersionDBOpts uses IncreaseParallelism(runtime.NumCPU()).

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 20, 2026 22:06 UTC
    Code Review
    versiondb/tsrocksdb/compact.go:1
    @@ -0,0 +1,73 @@
    +package tsrocksdb
    +
    +import (
    +	"errors"
    +	"fmt"
    +
    +	"github.com/linxGnu/grocksdb"
    +)
    +
    +// CompactVersionDB rewrites every sst file of the versiondb column family, bottommost level included,
    +// with the current compression options. rateBytesPerSec caps flush and compaction writes, 0 means unlimited.
    +func CompactVersionDB(dir string, rateBytesPerSec int64) (before, after uint64, err error) {
    +	if rateBytesPerSec < 0 {
    +		return 0, 0, fmt.Errorf("negative rate limit: %d", rateBytesPerSec)
    +	}
    +	db, cfHandle, err := openVersionDB(dir, compactionDBOpts(rateBytesPerSec))
    +	if err != nil {
    +		return 0, 0, fmt.Errorf("open versiondb: %w", err)
    +	}
    +	defer func() {
    +		cfHandle.Destroy()
    +		db.Close()
    +	}()
    +
    +	before, err = liveSSTFilesSize(db, cfHandle)
    +	if err != nil {
    +		return 0, 0, err
    +	}
    +	oldFiles := liveSSTFiles(db)
    +	compactOpts := grocksdb.NewCompactRangeOptions()
    +	defer compactOpts.Destroy()
    +	// not KForceOptimized: rocksdb 10.x can leave a bottommost file that sits after one the same compaction wrote
    +	compactOpts.SetBottommostLevelCompaction(grocksdb.KForce)
    +	db.CompactRangeCFOpt(cfHandle, grocksdb.Range{}, compactOpts)
    +
    +	// CompactRangeCFOpt returns no status, a failed compaction only shows up as a background error
    +	bgErrors, ok := db.GetIntProperty("rocksdb.background-errors")
    +	if !ok {
    +		return 0, 0, errors.New("failed to read rocksdb.background-errors")
    +	}
    +	if bgErrors > 0 {
    +		return 0, 0, fmt.Errorf("compaction failed with %d background errors, see the rocksdb LOG file", bgErrors)
    +	}
    +	for name := range liveSSTFiles(db) {
    +		if _, ok := oldFiles[name]; ok {
    +			return 0, 0, fmt.Errorf("sst file %s was not rewritten", name)
    +		}
    +	}

    CodeQL / Iteration over map

    Iteration over map may be a possible source of non-determinism

    Show more details

    JayT106 JayT106 commented on code on Oct 20, 2026 22:08 UTC
    Code Review
    versiondb/tsrocksdb/compact.go:1
    @@ -0,0 +1,73 @@
    +package tsrocksdb
    +
    +import (
    +	"errors"
    +	"fmt"
    +
    +	"github.com/linxGnu/grocksdb"
    +)
    +
    +// CompactVersionDB rewrites every sst file of the versiondb column family, bottommost level included,
    +// with the current compression options. rateBytesPerSec caps flush and compaction writes, 0 means unlimited.
    +func CompactVersionDB(dir string, rateBytesPerSec int64) (before, after uint64, err error) {
    +	if rateBytesPerSec < 0 {
    +		return 0, 0, fmt.Errorf("negative rate limit: %d", rateBytesPerSec)
    +	}
    +	db, cfHandle, err := openVersionDB(dir, compactionDBOpts(rateBytesPerSec))
    +	if err != nil {
    +		return 0, 0, fmt.Errorf("open versiondb: %w", err)
    +	}
    +	defer func() {
    +		cfHandle.Destroy()
    +		db.Close()
    +	}()
    +
    +	before, err = liveSSTFilesSize(db, cfHandle)
    +	if err != nil {
    +		return 0, 0, err
    +	}
    +	oldFiles := liveSSTFiles(db)
    +	compactOpts := grocksdb.NewCompactRangeOptions()
    +	defer compactOpts.Destroy()
    +	// not KForceOptimized: rocksdb 10.x can leave a bottommost file that sits after one the same compaction wrote
    +	compactOpts.SetBottommostLevelCompaction(grocksdb.KForce)
    +	db.CompactRangeCFOpt(cfHandle, grocksdb.Range{}, compactOpts)
    +
    +	// CompactRangeCFOpt returns no status, a failed compaction only shows up as a background error
    +	bgErrors, ok := db.GetIntProperty("rocksdb.background-errors")
    +	if !ok {
    +		return 0, 0, errors.New("failed to read rocksdb.background-errors")
    +	}
    +	if bgErrors > 0 {
    +		return 0, 0, fmt.Errorf("compaction failed with %d background errors, see the rocksdb LOG file", bgErrors)
    +	}
    +	for name := range liveSSTFiles(db) {
    +		if _, ok := oldFiles[name]; ok {
    +			return 0, 0, fmt.Errorf("sst file %s was not rewritten", name)
    +		}
    +	}

    Done in c26de1c: the check now ranges over GetLiveFilesMetaData() (a slice) and only looks names up in the map, so the first surviving file reported is deterministic. It runs in an offline CLI command, not consensus code.

    thomas-nguy thomas-nguy approved these changes on Oct 23, 2026 01:25 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    JayT106 JayT106
    Labels
    risk: low confidence: 90.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 53.6% (MEDIUM) · Higher = larger blast radius
    53.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90.7% · Lower = rushed or shallow review
    90.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 5.0% · Safe to merge
    5.0%