Skip to content

feat(cache): add a second-chance eviction policy and let policies observe reads - #1955

Merged
mbrandenburger merged 2 commits into
hyperledger-labs:mainfrom
sid200727:feat/evictionpolicy-touch-1917
Oct 12, 2026
Merged

mbrandenburger merged 2 commits into
hyperledger-labs:mainfrom
sid200727:feat/evictionpolicy-touch-1917

Conversation

@sid200727

@sid200727 sid200727 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2041 (Steps 2) and #2042 (Step 3) of #1917, where @mbrandenburger confirmed approach A.

EvictionPolicy has one hook, Push, called from Put and from Update when it adds a key. That is enough for LRU, which fixes an entry's position at insertion, and for timeout eviction, which expires entries by age since insertion. Second-chance (CLOCK) eviction also needs to know when an entry is read, which is what secondcache.getLocked does today. This PR adds that hook and a second-chance policy that uses it, so the new hook has a consumer from the start.

Step 2: EvictionPolicy.Touch

evictionCache.Get calls Touch(key) on a hit and does nothing on a miss. Push runs under the cache's write lock, but Get holds only a read lock, so Touch can run concurrently with itself and must do its own locking. The interface comment says so. LRU and timeout implement Touch as a no-op, so existing caches behave the same as before. The mock policy records touches, and TestEvictionCacheGetTouches checks that a hit touches and a miss does not.

Step 3: second-chance policy

NewSecondChanceCache(size, buffer, onEvict) returns a Map backed by evictionCache and the new secondChanceEviction policy:

  • Keys live in a ring of size slots, each with a referenced bit. Touch, and Put on a key the policy already tracks, set the bit.
  • When no slot is free, the victim scan walks the ring, clears referenced bits as it passes, and evicts unreferenced entries until it has freed buffer slots. buffer is clamped to [1, size].
  • size is the maximum number of entries the cache holds. NewLRUCache treats size as a guaranteed minimum.
  • evictionCache.Delete does not notify the policy, so a slot can outlive its entry. The policy receives a present callback, and the scan uses it to reclaim such slots without reporting them as evicted. A key that is deleted and then added again reuses its slot.

No consumer is migrated in this PR, and secondcache stays in use. The KVS, MSP and vault caches move over in later steps of #1917, in the order listed there.

Known issue

With buffer > 1, a scan that wraps around the ring can free the same slot twice, which orphans an entry and lets the cache exceed size. This is tracked, together with the related secondcache bug, in #1985.

Tests

second_chance_test.go covers a referenced entry surviving a scan, eviction order without reads, the size bound under churn, the onEvict payload, reclaiming the slot of a deleted key, re-adding a deleted key, size 1, and concurrent Get/Put under -race.

@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Hey @sid200727 👋 thanks for the PR!
I'm your friendly PR Helper Bot 🤖 and I'll be riding shotgun on this one, keeping track of your PR's status to help you get it approved and merged.

This comment updates automatically as you push changes -- think of it as your PR's live scoreboard!
Here's the latest:


PR Checks

✅ DCO Sign-off -- All commits have valid sign-offs. Nice work!


❌ GPG Signature -- Heads up! The following commits don't have a verified GPG signature:

  • b7c9b79 feat(cache): let an eviction policy observe reads
  • 72578ea feat(cache): add a second-chance eviction policy

You'll need to sign your commits with GPG (e.g. git commit -S). See the Signing Guide for a step-by-step walkthrough.


✅ Merge Conflicts -- No merge conflicts detected. Smooth sailing!


✅ Issue Link -- Linked to #2041, #2042 (assigned to you).


⏳ All checks must pass before this PR can be reviewed. You've got this!

@github-actions github-actions Bot added the status: needs revision The pull request requires changes from the author before it can be reviewed or merged label Sep 30, 2026
@sid200727
sid200727 force-pushed the feat/evictionpolicy-touch-1917 branch from 1805bda to 5f6771f Compare September 30, 2026 07:05
@sid200727

Copy link
Copy Markdown
Contributor Author

@mbrandenburger the PR-helper bot wants a closing keyword, but #1917 has six steps and this is step 2, closing it here would be wrong. Should I split the remaining steps into their own sub-issues so each PR closes one, or can the bot check be waived for this?
though I am assigned to the issue mentioned in the pr.
Thank you !

@mbrandenburger

Copy link
Copy Markdown
Member

@sid200727 got it - let's create subtasks for #1917, so this becomes easy to follow where we are.

@mbrandenburger mbrandenburger added this to the 26Q3 milestone Sep 30, 2026
@mbrandenburger
mbrandenburger self-requested a review September 30, 2026 08:13
@mbrandenburger mbrandenburger modified the milestones: 26Q3, 26Q4 Sep 30, 2026
@mbrandenburger

Copy link
Copy Markdown
Member

@sid200727 moreover, I believe we could also add Step 3 into this PR; so we have a "consumer" of Touch here. WDYT?

@sid200727

Copy link
Copy Markdown
Contributor Author

@mbrandenburger yes, it makes sense a Touch with no consumer isn't really reviewable. I'll create subtasks for steps 2–6 on #1917 and point this PR at both the step-2 and step-3 ones, so the board still tracks each step but they land together.

Working on the second-chance policy now; will push it onto this branch.
Thank you !

@sid200727

Copy link
Copy Markdown
Contributor Author

Hi @mbrandenburger !
Starting step 3 and hit something worth deciding before I write it.

secondcache.Delete doesn't delete, it zeroes the value and sets referenced = 1, leaving the key in the table. So a later Get returns (zero, true) rather than a miss, and the entry gets a second chance in the next victim scan instead of being reclaimed. All three consumers already work around it: kvs.go:80 and :100 check len(raw) > 0, kvs.go:161 checks cachedRaw != nil, and vault/cache.go:68 has ok && e != nil with the comment "Deleted entries return ok".

The typed variant also writes the new item into buffer slots during one victim scan (addLocked keeps assigning &item each time it finds a victim), so items accumulates duplicates and effective capacity drops. The bytes variant returns after the first victim and is fine.

The port naturally does the right thing on both, since the policy only tracks keys and the cache owns storage. Do you want step 3 to just fix them as part of the fold, or should these go in as their own sub-issues under #1861 first so the fold is a pure refactor?

@mbrandenburger

Copy link
Copy Markdown
Member

@sid200727 thanks, good catches.

The victim scan bug is now tracked in #1985. All consumers keep using secondcache until step 5, so let's fix it there separately and keep step 3 a pure port. If step 5 lands before, #1985 becomes obsolete.

For Delete, I'd leave the tombstone in secondcache alone, since the package goes away in step 6, and have the new cache just delete. That changes behaviour when each consumer migrates, so the step 5 PRs should call it out and remove the workarounds. In KVS, Get after Delete fails with an unmarshal error today instead of "does not exist", and TestKVS_Cache only asserts require.Error, so the KVS migration should tighten that test.

One thing to watch in step 3: evictionCache.Delete doesn't tell the policy, so a second-chance policy would keep a stale slot for the deleted key and could later evict a re-added entry through it. Either notify the policy on Delete or skip keys no longer in the map.

Once the sub-issues for #1917 exist, please link the step 2 and step 3 ones here so the bot check passes.

@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown

👋 Hey @sid200727! This PR has been inactive for 5 days.

Are you still working on this? We will close this in 2 days if we see no further activity.

If you're still on it, leave a comment to let us know! If you'd like to step down, comment /unassign.

@sid200727
sid200727 force-pushed the feat/evictionpolicy-touch-1917 branch from 5f6771f to 93c5ba7 Compare October 8, 2026 06:37
@mbrandenburger mbrandenburger changed the title feat(cache): let an eviction policy observe reads feat(cache): add a second-chance eviction policy and let policies observe reads Oct 12, 2026
@mbrandenburger mbrandenburger linked an issue Oct 12, 2026 that may be closed by this pull request
EvictionPolicy had a single hook, Push, called from Put and from Update
when it adds a key. That is enough for the two policies in the tree: LRU
here fixes an entry's position at insertion, and timeout eviction expires
on age since insertion. It is not enough for second-chance eviction, which
has to mark an entry as recently used on every Get, and which hyperledger-labs#1917 folds
into this package.

Add Touch to the interface and call it from evictionCache.Get on a hit. Its
contract differs from Push's and the interface says so: Get holds only a
read lock, so Touch can run concurrently with itself and must do its own
locking, whereas Push is documented as running under the write lock.

Both existing policies implement Touch as a no-op, so there is no behaviour
change. The mock policy in eviction_test.go now records touches, and a new
test asserts Get touches on a hit and not on a miss.

First step of hyperledger-labs#1917.

Signed-off-by: Siddhi Khandelwal <siddhi.200727@gmail.com>
Ports the CLOCK logic out of secondcache into an EvictionPolicy under
utils/cache, with NewSecondChanceCache mirroring NewLRUCache. The policy
owns the slot ring and referenced bits; the cache keeps owning values.

evictionCache.Delete does not notify the policy, so the victim scan
reclaims slots whose key is no longer in the map instead of spending a
second chance on them, and Push reuses a key's existing slot.

Signed-off-by: Siddhi Khandelwal <siddhi.200727@gmail.com>
@mbrandenburger
mbrandenburger force-pushed the feat/evictionpolicy-touch-1917 branch from b1a3e09 to 72578ea Compare October 12, 2026 10:22
@mergify

mergify Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

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

Labels

status: needs revision The pull request requires changes from the author before it can be reviewed or merged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add a second-chance eviction policy under utils/cache Extend EvictionPolicy with a read hook and wire it from evictionCache.Get

2 participants