You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
CBG-5898: Compact document channel history on write - #9126
When enable_channel_history_compaction is true, a document write removes the channel history that ended at or before the purge sequence.
TimestampsManager.GetPurgeSequence computes PurgeTimestamp = now - purge_interval and reads the in-memory timestamps array. It returns array[0].seq if array[0].t <= PurgeTimestamp, and 0 otherwise, which follows the rule in the design doc.
documentUpdateFunc calls CompactHistory with the purge sequence and logs the compacted channels at debug level (base.UD). If compaction is disabled or the purge sequence is 0, the write skips this step.
NewDatabaseContext now creates the TimestampsManager, and StartOnlineProcesses only starts it. The import feed starts before the manager did, so an import during startup called GetPurgeSequence on a nil manager and the document was not imported. Until Start runs, GetPurgeSequence loads the timestamps document when the in-memory array is empty.
If the timestamps document is missing, Start now writes it with one entry for the current sequence, not an empty array. The first entry no longer waits for the next run of the background task.
Tests set the clock of the manager with test-only helpers in db/timestamps_seq_test.go, not with an option on DatabaseContextOptions.
Pre-review checklist
Logging sensitive data? Make sure it's tagged (e.g. base.UD(docID), base.MD(dbName))
Updated relevant information in the API specifications (such as endpoint descriptions, schemas, ...) in docs/api
The reason will be displayed to describe this comment to others. Learn more.
🟢 Approval recommended
No active review issues remain for the optional write-time channel-history compaction change.
No open issues 🎉
What changed in this PR
Adds write-time compaction of document channel history in Sync Gateway when enable_channel_history_compaction is enabled, using the purge sequence derived from cached timestamps.
Changes:
Removes channel history ending at or before the purge sequence and logs compacted channels with user-data redaction.
Creates the timestamps manager before imports can begin, while keeping its background startup in the online lifecycle.
Adds coverage for purge boundaries, enabled and disabled compaction, startup imports, and offline manager state.
File
Description
rest/timestamps_seq_test.go
Checks that the timestamps manager is stopped while offline.
rest/importtest/import_test.go
Tests importing pre-existing documents with compaction enabled.
db/util_testing.go
Adds a test helper for timestamps-manager running state.
db/timestamps_seq.go
Computes the purge sequence from cached timestamps.
db/timestamps_seq_test.go
Tests purge-sequence selection and write-time compaction.
db/database.go
Initializes the manager earlier and adds a test clock option.
The reason will be displayed to describe this comment to others. Learn more.
It looks like other code went in on previous PRs that I'm equally unhappy about but see comments below for this PR in particular.
Tldr:
KV Get amplification until the manager has stored a timestmap (which takes 10 mins? I had made a comment in an earlier PR to write a timestamp/sequence before the ticker to ensure there's always one present)
Don't like the test seams/functions where possible to avoid
two bools for started/stopped state is confusing in how they are used
When enable_channel_history_compaction is true, a document write removes
the channel history that ended at or before the purge sequence.
- TimestampsManager.GetPurgeSequence returns the sequence of the oldest
timestamps entry if that entry is at or before now - purge_interval.
Otherwise it returns 0, and the write purges nothing.
- documentUpdateFunc calls CompactHistory with the purge sequence, and
logs the compacted channels at debug level with redacted names.
- NewDatabaseContext creates the TimestampsManager, and
StartOnlineProcesses only starts it. The import feed starts before
the manager did, so an early import called GetPurgeSequence on a nil
manager.
- DatabaseContextOptions.TestTimestampsNowFunc sets the clock of the
manager in tests.
The tests cover purgeSequence, GetPurgeSequence, compaction with the
option on and off, and the import of documents that exist before the
database starts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts:
# db/database.go
# db/timestamps_seq_test.go
- Set an atomic started flag in Start, so that IsRunningForTest does
not read backgroundTasks while Start appends to it on another
goroutine.
- Add TimestampsManager.purgeTimestamp, so that trim and
GetPurgeSequence use the same start of the purge interval.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- GetPurgeSequence loads the timestamps document when the in-memory
array is empty, so that documents imported before Start are
compacted.
- checkEntry calls addEntry on every check, so that the in-memory
array picks up trims and invalid-entry removals by other nodes
within one check interval.
- Create the TimestampsManager only in NewDatabaseContext, with the
idle KV op store and the test clock.
- Add tests for imports before Start, a failed addEntry in Start,
and compaction of documents imported when a database starts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Start now writes an entry with the current sequence when the timestamps
document is missing, and GetPurgeSequence uses the array that it loads.
The clock of the TimestampsManager is set by test-only helpers, not by
DatabaseContextOptions. One atomic state replaces the started and
stopped flags, and IsRunning replaces IsRunningForTest.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FetchTimestampsSeqArray reads the cluster sequence and drops the entries
above it before it updates the in-memory array. A write before Start can
no longer use an entry from before a sequence rollback to compact a new
channel removal. If the sequence read fails, the in-memory array stays
unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Cached cutoffs can bypass rollback validation and delete fresh channel removals, losing replication notifications, while request-triggered reads are incorrectly counted as idle operations.
No open issues 🎉
2 previously missed issues
In code that hasn't changed since last review
Stale cached cutoffs can delete removals after sequence rollback
db/timestamps_seq.go:371
A populated cache bypasses rollback validation: a quiet node can retain another node's expired cutoff of 1000 while a rolled-back sequence counter allocates a fresh removal at sequence 20. Before the next background check, write-time compaction then deletes that fresh removal from ChannelSet and doc.Channels, losing its replication notification. Invalidate cached cutoffs on rollback, reject cutoffs at or above the current write's sequence, and add a regression with a populated cache.
Request-triggered fetches are incorrectly counted as idle KV operations
db/timestamps_seq.go:372
This fetch runs during REST/BLIP writes, but both its datastore and sequence callback use the permanently idle-counted store. If the timestamps array stays empty, such as after resetting a corrupt timestamps document, client-triggered reads incorrectly increase idle_kv_ops, hiding those operations from activity accounting. Use uncounted dependencies for request-triggered fetches while retaining idle counting for background maintenance.
The reason will be displayed to describe this comment to others. Learn more.
Not sure how this change addresses the empty/missing timestamp doc on start. The symptom/issue is the same even after changing addEntry to seed an initial value if there's no timestamp doc present yet.
The reason will be displayed to describe this comment to others. Learn more.
My mistake - but would we actually prefer the tighter assertion (greater than not equal) on platforms other than windows here? Or do we actually expect equal values?
The reason will be displayed to describe this comment to others. Learn more.
What scenario would we expect this to return equal values - assuming time was ticking upwards correctly?
Unless I'm misreading - that would require these two lines to run to completion in the same instant?
The reason will be displayed to describe this comment to others. Learn more.
When I just use assert.Greater the test is flaky, on my machine, the values are the same, not sure why. Your understanding of TakeDbOnline should take more time is valid, but I've based this on what I observe from the tests
The reason will be displayed to describe this comment to others. Learn more.
What scenario would we expect this to return equal values - assuming time was ticking upwards correctly?
Unless I'm misreading - that would require these two lines to run to completion in the same instant?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
CBG-5898
When
enable_channel_history_compactionis true, a document write removes the channel history that ended at or before the purge sequence.TimestampsManager.GetPurgeSequencecomputesPurgeTimestamp = now - purge_intervaland reads the in-memory timestamps array. It returnsarray[0].seqifarray[0].t <= PurgeTimestamp, and 0 otherwise, which follows the rule in the design doc.documentUpdateFunccallsCompactHistorywith the purge sequence and logs the compacted channels at debug level (base.UD). If compaction is disabled or the purge sequence is 0, the write skips this step.NewDatabaseContextnow creates theTimestampsManager, andStartOnlineProcessesonly starts it. The import feed starts before the manager did, so an import during startup calledGetPurgeSequenceon a nil manager and the document was not imported. UntilStartruns,GetPurgeSequenceloads the timestamps document when the in-memory array is empty.Startnow writes it with one entry for the current sequence, not an empty array. The first entry no longer waits for the next run of the background task.db/timestamps_seq_test.go, not with an option onDatabaseContextOptions.Pre-review checklist
base.UD(docID),base.MD(dbName))docs/apiDependencies (if applicable)
Integration Tests
🤖 Generated with Claude Code