Skip to content

CBG-5898: Compact document channel history on write - #9126

Open
RIT3shSapata wants to merge 8 commits into
mainfrom
CBG-5898
Open

RIT3shSapata wants to merge 8 commits into
mainfrom
CBG-5898

Conversation

@RIT3shSapata

@RIT3shSapata RIT3shSapata commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

CBG-5898

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

Dependencies (if applicable)

  • Link upstream PRs
  • Update Go module dependencies when merged

Integration Tests

🤖 Generated with Claude Code

@RIT3shSapata
RIT3shSapata requested review from a team November 16, 2026 14:19
Copilot AI balanced review requested due to automatic review settings November 16, 2026 14:19
@factory-droid

factory-droid Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Droid finished @RIT3shSapata's task —— View job


LGTM — no issues found.

0 inline comments posted

Copilot AI 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.

🟢 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.
db/​crud.go Compacts channel history on writes when enabled.

Review effort: Balanced

@torcolvin torcolvin left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I didn't verify claude's finding about import but it reads correct to me.

Comment thread db/database.go Resolved
Comment thread db/timestamps_seq.go Resolved
Comment thread db/timestamps_seq.go Resolved
Comment thread rest/importtest/import_test.go Resolved
Comment thread db/util_testing.go Resolved

@bbrks bbrks left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Comment thread db/timestamps_seq.go Resolved
Comment thread db/timestamps_seq.go Resolved
Comment thread db/timestamps_seq.go Resolved
Comment thread db/database.go Resolved
Comment thread db/util_testing.go Resolved
@bbrks bbrks assigned RIT3shSapata and unassigned bbrks Nov 18, 2026
RIT3shSapata and others added 4 commits December 2, 2026 13:30
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>
@RIT3shSapata
RIT3shSapata requested review from bbrks and a balanced review from Copilot December 2, 2026 08:03
@RIT3shSapata RIT3shSapata removed their assignment Dec 2, 2026

Copilot AI 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.

🟡 Changes recommended

The startup read bypasses rollback validation, allowing stale timestamp entries to delete fresh channel removals after a cluster counter rollback.

1 open issue

Review effort: Balanced

Comment thread db/timestamps_seq.go Resolved
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>

Copilot AI 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.

🔵 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

High severity 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.

Medium severity 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.

1 resolved since last review

Review effort: Balanced

@bbrks bbrks left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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.

require.Len(t, tsDoc.Timestamps, 0)
require.Len(t, tsDoc.Timestamps, 1)
assert.GreaterOrEqual(t, tsDoc.Timestamps[0].Seq, lastSeq)
assert.GreaterOrEqual(t, tsDoc.Timestamps[0].Timestamp, beforeOnline)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This will probably have to use base.AssertTimestampGreaterThan to avoid a flake on Windows where time resolution is poor.

@RIT3shSapata RIT3shSapata Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

AssertTimestampGreaterThan uses assert.GreaterOrEqual for windows, which is what the test currently uses.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes we expect equal values

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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?

	beforeOnline := time.Now().Unix()
	rt.TakeDbOnline()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Comment thread db/timestamps_seq.go Resolved
Comment thread db/timestamps_seq.go Resolved
Comment thread db/timestamps_seq.go
Comment on lines -190 to -192
if !tm.entryDue() {
return nil
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This was the only non-test use of entryDue - what's now preventing checkEntry from always adding a value?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

checkEntry will not always add a value, because this deleted code was just duplicate of what already exists inside addEntry. Permalink

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

If so, I think we need to remove checkEntry then? This is a wrapper function that is adding no value.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I agree, will remove it

Comment thread db/timestamps_seq.go Resolved
Comment thread db/timestamps_seq.go Resolved
@bbrks bbrks assigned RIT3shSapata and unassigned bbrks Dec 2, 2026
@RIT3shSapata
RIT3shSapata requested a review from bbrks December 3, 2026 09:52
@RIT3shSapata RIT3shSapata assigned bbrks and unassigned RIT3shSapata Dec 3, 2026
…estamps doc

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread db/crud.go Resolved
Comment thread db/timestamps_seq.go
Comment on lines -190 to -192
if !tm.entryDue() {
return nil
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

If so, I think we need to remove checkEntry then? This is a wrapper function that is adding no value.

Comment thread db/timestamps_seq.go Resolved
require.Len(t, tsDoc.Timestamps, 0)
require.Len(t, tsDoc.Timestamps, 1)
assert.GreaterOrEqual(t, tsDoc.Timestamps[0].Seq, lastSeq)
assert.GreaterOrEqual(t, tsDoc.Timestamps[0].Timestamp, beforeOnline)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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?

	beforeOnline := time.Now().Unix()
	rt.TakeDbOnline()

@bbrks bbrks assigned RIT3shSapata and unassigned bbrks Dec 3, 2026
RIT3shSapata and others added 2 commits December 4, 2026 19:26
…the background task

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ite's sequence

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@RIT3shSapata
RIT3shSapata requested a review from bbrks December 4, 2026 17:17
@RIT3shSapata RIT3shSapata assigned bbrks and unassigned RIT3shSapata Dec 4, 2026

This branch has not been deployed

No deployments
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.

4 participants