Skip to content

Releases

v0.6.1

Choose a tag to compare

@dwisiswant0 dwisiswant0 released this 17 Nov 19:23
995bea4

This release removes a pause of tens of milliseconds from the first insert after many deletes. It also corrects three docs: how to restore a weighted cache, a case where saving silently drops struct fields, and the README's allocation claims. The exported API and the file format are unchanged: file.go changed only in doc comments, so v0.6.1 reads and writes the same data as v0.6.0. The fix makes inserts into a full cache slower on the CPU it was measured on (see Performance).

Fixed

  • The first Set after many deletes no longer stalls. Delete leaves its slot in the cache's FIFO order log. Once dead slots outnumbered live entries by more than 1,024, the next insert checked every slot in the log while holding the cache-wide queue lock. At a million entries that insert took tens of milliseconds, and every other insert of a new key waited behind it. Compaction now runs a few slots per insert, so the time an insert spends on the log no longer depends on the cache size. Delete stays O(1) amortized, and eviction order is unchanged. (#72, fixes #76)

Performance

Measured against v0.6.0 on a 16-vCPU AMD EPYC 7763 with Go 1.27.4:

  • First Set after deleting 60% of a million entries: about 50 ms before, about 3 µs now.
  • Delete-and-insert churn at a million entries: the slowest Set drops from about 150 ms to about 100 ms. What remains is one growth of the log's buffer. The average Set is about 15% slower.
  • Inserts into a full cache with no deletes: about 16% slower at a million entries and about 4% at 64K, although no compaction runs in that workload. Each changed line applied alone to v0.6.0 costs nothing, so this looks like a microarchitectural effect rather than added work. The exact cause hasn't been found.
  • Memory: at a million entries under churn, the log is longer while a pass runs, which costs one more growth step. Its peak goes from 2.10M to 2.40M slots, and the heap from 158 MiB to 171 MiB.
  • Everything else: the other 15 benchmarks in the same comparison, including Get, Delete, Set replacing a value and loading, showed no change.

Trade-offs

  • A workload that never deletes pays the full-cache insert cost and gets nothing from the fix.
  • The slowdown was measured only on that Zen 3 machine. Laptop runs on Apple Silicon were too noisy to confirm or rule it out.

Documentation

  • Restoring a weighted cache. LoadFrom, LoadFromFile and LoadFromFileOrNew build the cache with New, so a cache made by NewWeighted loads back without its weight bound. One made with math.MaxInt as maxEntries, the documented way to bound a cache by weight alone, loads back with no bound at all. The docs for NewWeighted, the three load functions and the package, and the README, now say so and give the way to restore one: make a new cache with NewWeighted and the same arguments, then pass its Set to LoadFromFunc. The new ExampleLoadFromFunc_weighted restores a weighted cache from a file and shows that it still evicts. (#73)

    // LoadFromFile would drop the weight bound.
    cache, err := fastcache.NewWeighted(math.MaxInt, 64<<20, weigh)
    if err != nil {
    	return err
    }
    
    f, err := os.Open(path)
    if err != nil {
    	return err
    }
    defer f.Close()
    
    if err := fastcache.LoadFromFunc(f, cache.Set); err != nil {
    	cache.Reset() // Drop the entries loaded before the error.
    	return err
    }
  • Saving can't detect fields dropped from a struct that embeds a type with a GobEncode or MarshalBinary method, such as time.Time. The struct inherits the method, so gob encodes only the embedded value. SaveTo and LoadFrom both return nil, and the struct's other fields load back as zero values. In a key, entries whose keys differed only in those fields load back as one entry. The save docs promised an error for any field gob would drop. SaveTo now describes this case and its fixes: give the embedded field a name, or, for values, convert them with SaveToFunc. SaveToFile, SaveToFileConcurrent and SaveToFunc point to it, and SaveToFunc adds that neither K nor S should embed such a type. The check itself can't be fixed: reflection can't tell an inherited method from one the struct declares, so it would also reject structs that declare their own GobEncode and save correctly. (#74, closes #77)

  • The README's allocation claims are scoped. The README said Get doesn't allocate, which holds only for string keys. Hashing other key types boxes the key, so a struct key allocates once on every Get, and so does an int key of 256 or more. Every Set allocates the entry it stores, not only a Set that replaces a value. The features list, the comparison table and the benchmark highlights now say so. The table's cell for the original fastcache now reads "Get with nil dst: 1 per hit. Set: 0". The highlights also explain why its allocs/op shows 0 from Get/256 up: some of those Get calls miss, and the average, below 1, is truncated to an integer. (#75)

Internal

  • The order log is compacted in place, at most compactStep (8) slots per insert. The ring counts a pass's holes and unchecked slots from the newest end, so pushFront is unchanged and pop still inlines. When evictions have taken every slot a pass kept, pop drops the holes and ends the pass, and the next insert starts a new one if dead slots still outnumber live ones. (#72)
  • TestCacheCompactsOrderLogInSmallSteps checks that an insert after mass deletes doesn't rewrite the whole log. TestSlotRingKeepsFIFOOrder now runs compaction passes between pushes and pops, and the churn test bounds how much the log can grow while a pass runs. (#72)

Full changelog: v0.6.0...v0.6.1

v0.6.0

Choose a tag to compare

@dwisiswant0 dwisiswant0 released this 16 Nov 14:24
3623559

This release adds NewWeighted, which bounds a cache by the total weight of its entries, such as the bytes of their values, as well as by entry count. Caches made by New behave as before, but each entry now stores a weight, so some of their writes are slightly slower (see Performance). The file format is unchanged: weights aren't saved, and v0.6.0 reads and writes the same data as v0.5.1.

// At most 1,000 entries whose values add up to at most 64 MiB.
cache, err := fastcache.NewWeighted(1000, 64<<20, func(_ string, v []byte) int {
	return len(v)
})

Added

  • NewWeighted(maxEntries, maxWeight, weigh) returns a cache that holds at most maxEntries entries whose weights add up to at most maxWeight. You supply weigh, a func(K, V) int, such as one that returns the length of the value. (#71, closes #70)
    • When a new or heavier value doesn't fit, the oldest entries are evicted until it does. A Set that makes a value heavier evicts only other entries, so its key stays in the cache and keeps its place in eviction order.
    • Each entry keeps the weight it was stored with, so the total can't drift if data that a value points to changes later.
    • To bound a cache by weight alone, pass math.MaxInt as maxEntries. Storage is allocated as entries are stored, not up front.
  • ErrInvalidWeight is returned by Set, GetOrSet and SetIfAbsent in a weighted cache when a value's weight is negative or greater than maxWeight. The cache is left unchanged. GetOrSet and SetIfAbsent check the weight only when the key is absent. (#71)
  • ErrInvalidMaxWeight is returned by NewWeighted when maxWeight isn't positive. NewWeighted also returns an error when weigh is nil, and the same errors as New for an invalid maxEntries. (#71)

Saving and loading weighted caches

  • Weighted caches save like any other cache. Their weights aren't saved.
  • LoadFrom, LoadFromFile and LoadFromFileOrNew return caches bounded only by entry count. To load saved entries into a weighted cache, pass its Set to LoadFromFunc, which stops with ErrInvalidWeight at the first saved value heavier than maxWeight. (#71)

Performance

Each entry now stores its weight, which makes it 8 bytes larger, in caches made by New too. Measured against v0.5.1 on an Apple M5 Pro:

  • Get: 1.5% slower (about 0.15 ns), with no change in allocations.
  • Updates of [string, []byte], the type the README benchmarks: 3% slower, with no change in memory.
  • Small types such as [string, string] and [int, int]: the extra 8 bytes move each entry up an allocation size class. Updates take 8% to 10% longer and allocate 16 B more, and each stored entry takes 16 B more memory. Inserts into a full [int, int] cache take 9% longer.
  • Benchmark suite (GOMAXPROCS=4): the geomean is within 0.05% of v0.5.1's (48.52 ns against 48.50 ns), and the fork is still 2.4× faster than the original fastcache and otter. Set is 3% to 8% slower from 16 to 1,024 keys, SetGet 1% to 8% slower up to 2,048 keys, and SetParallel 5% to 6% slower at 1 and 16 keys. From 4,096 keys up there is no measurable change.

Trade-offs

  • In a weighted cache, an update that makes a value heavier locks the cache-wide FIFO queue, as adding a key does, because it may have to evict. Updates that add no weight still lock only the key's shard. (#71)
  • The benchmark suite measures only caches made by New, not NewWeighted.

Documentation

  • The README lists weighted capacity among the features and in the comparison with the original fastcache, and no longer lists "No size-based limits" under Limitations. (#71)
  • The README's benchmark table was rerun on this release with the same settings. Its geomean now reads 48.5 ns against 116.2 ns for otter and 118.4 ns for the original. The changed GetParallel ranges reflect run-to-run spread, not the new code. (#71)

Internal

  • Each entry records its weight, and the cache keeps a running total that inserts, updates, deletes, evictions and Reset adjust. Eviction can skip the entry being updated and return it to the front of the queue. (#71)

Full changelog: v0.5.1...v0.6.0

v0.5.1

Choose a tag to compare

@dwisiswant0 dwisiswant0 released this 16 Nov 03:57
d99899e

This release fixes four bugs in saving and loading: a goroutine leak after a failed save, a hang when saving into a pipe, damaged data that reached LoadFromFunc as wrong values, and errors that errors.Is couldn't match. The exported API and the file format are unchanged: v0.5.1 writes the same bytes as v0.5.0, and each loads what the other saves.

Warning

Behavior change:

  • Loading checks the end of the saved data. LoadFrom, LoadFromFile, LoadFromFunc and LoadFromFileOrNew now read the end-of-stream chunk that minlz writes after the last entry, and reading it checks the stream's length. Data whose end chunk is missing or wrong, or that continues after the last entry, now fails to load. Before this release it loaded. Every successful save writes a valid end chunk, so only damaged or cut-off data is affected, such as a connection that closed right after the last entry. LoadFromFunc has already passed every entry to its function when it reports this error, and LoadFromFileOrNew returns an empty cache, as it does for any file it can't load. (#67, fixes #64)

Fixed

  • A failed save no longer leaves a goroutine running. The minlz writer runs a goroutine until it is closed, and saving closed it only when the save succeeded. Each SaveTo, SaveToFile, SaveToFileConcurrent or SaveToFunc whose writer failed partway, such as on a full disk or a closed connection, left one more goroutine waiting forever. (#65, fixes #61)
  • SaveTo into a pipe returns once the other end has loaded the data. LoadFrom and LoadFromFunc stopped reading at the last entry and never read the end chunk after it, so a SaveTo into an io.Pipe blocked forever writing that chunk. Loading now reads through the end chunk and stops there, without waiting for the writer to close. Because it no longer reads past the saved data, saves written one after another to the same stream also load one after another. In v0.5.0 the second load failed with minlz: corrupt input. (#67, fixes #64)
  • Damaged data no longer reaches LoadFromFunc's function as a wrong value. One damaged byte could make minlz skip a whole compressed chunk without a check. LoadFromFunc then passed the entry that spanned the gap, with different contents, and the error came only with a later entry. Loading now rejects such a chunk as minlz.ErrCorrupt as soon as it reads it, so no entry decoded across the gap is passed on. (#68, fixes #63)
  • Save and load errors wrap their cause. They kept only the text of the error that caused them, so errors.Is couldn't tell a full disk or a closed connection from damaged data. errors.Is and errors.As now match the writer's and reader's own errors, file-system errors from SaveToFile and SaveToFileConcurrent, and gob and minlz errors such as minlz.ErrCorrupt, so those errors are now part of what the functions return. Data that ends after the capacity but before all the entries it promises reports io.ErrUnexpectedEOF; only data that is empty from the start matches io.EOF. (#66, fixes #62)

Performance

  • Loading 100k entries takes the same time and memory as in v0.5.0. Saving runs the same code, apart from closing the writer on error paths.

Documentation

  • The docs for LoadFrom and LoadFromFunc now say that a successful load reads the reader to the end of the saved data and no further. (#67)

Internal

  • Loading reads through a small reader in front of minlz that ends after the end chunk and rejects chunk types that saving never writes. (#67, #68)

Full changelog: v0.5.0...v0.5.1

v0.5.0

Choose a tag to compare

@dwisiswant0 dwisiswant0 released this 15 Nov 09:27
f0865f8

This release adds iterators that walk the cache in eviction order, and functions that select and convert entries when saving and loading. LoadFromFileOrNew now creates the cache with the capacity you pass it. The file format is unchanged: data saved by v0.4.0 loads in v0.5.0, and data saved by v0.5.0 loads in v0.4.0.

Warning

Breaking change:

  • LoadFromFileOrNew uses the maxEntries you pass, not the saved capacity. Before this release it used maxEntries only when the file failed to load, and otherwise returned a cache with the capacity it was saved with. Saving writes that capacity back, so a program that changed its cache size kept the old one on every run until the file was deleted. Now the cache always has maxEntries capacity. When the file holds more entries than that, the cache keeps the newest and counts the others as evictions in Stats. A missing or corrupted file still gives an empty cache. (#59, fixes #55)
  • A maxEntries that isn't positive is now an error even when the file loads. (#59)
  • To keep the saved capacity, call LoadFromFile and fall back to New(maxEntries) when it returns an error. LoadFromFile and LoadFrom still restore the saved capacity.

Added

  • AllFIFO, KeysFIFO and ValuesFIFO iterate oldest first, which is the order in which the cache evicts. Updating a key keeps its place; deleting a key and setting it again makes it the newest. All, Keys and Values keep their faster, unordered iteration. (#57, closes #54)
  • SaveToFunc saves the entries that a function selects, as the values it returns, oldest first. Use it to save part of a cache, or to save values that gob can't encode, such as structs with unexported fields, by converting them to a type it can. The gob check applies to the returned type instead of V. (#58, closes #56)
  • LoadFromFunc passes each saved entry, oldest first, to a function, such as the Set method of a cache you already have. It ignores the saved capacity and returns the first error that the function returns. It reads what SaveTo, SaveToFile and SaveToFunc write, and LoadFrom reads what SaveToFunc writes. (#58, closes #56)

Performance

  • SaveTo is 4.8% faster on 500k entries, and SaveToFileConcurrent with 8 workers is 3.9% faster, because the oldest-first sort moves smaller references. (#57)
  • Get, Set, Delete, All, Keys and Values run the same code as in v0.4.0, and their benchmarks show no change.

Trade-offs

  • AllFIFO, KeysFIFO and ValuesFIFO copy and sort every entry before they yield the first one, and hold memory in proportion to Len until the loop ends. On 500k entries a full loop takes about 8× as long as with All, and a loop that stops after 10 entries about 17,000× as long. (#57)
  • SaveToFunc keeps the values it saves in memory until it writes them, because the format puts the entry count first. (#58)
  • LoadFromFileOrNew with a maxEntries smaller than the file's entry count still decodes every entry, then evicts the extras. (#59)

Internal

  • Saving and the FIFO iterators share one oldest-first snapshot. Its workers take every n-th shard instead of reading shard numbers from a channel. (#57)
  • All save and load functions share one encoder and one decoder. (#58)
  • LoadFrom no longer adds the entry's index to an error from inserting it. (#58)

Full changelog: v0.4.0...v0.5.0

v0.4.0

Choose a tag to compare

@dwisiswant0 dwisiswant0 released this 14 Nov 20:18
c9fdde8

This release fixes several FIFO eviction and persistence bugs, cuts memory use, and makes Get lock-free. The exported API is unchanged.

Warning

Behavior changes:

  • Saving rejects types it can't fully encode. SaveTo, SaveToFile and SaveToFileConcurrent now return an error, before writing anything, when K or V contains fields that gob drops: unexported struct fields, or chan and func fields. Before this release these values saved without an error and came back with those fields zeroed or nil. The error names the field and its path. To keep saving such a type, export its fields or implement gob.GobEncoder or encoding.BinaryMarshaler. The error isn't exported, so errors.Is can't match it. (#39, fixes #30)
  • Known gap: a struct that embeds a type that encodes itself, such as time.Time, still loses its other fields without an error.

Fixed

  • Set, GetOrSet and SetIfAbsent no longer return ErrEvictionFailed on a full cache when a concurrent Delete or GetAndDelete removes the entries being evicted. (#52, fixes #46)
  • A key that is deleted and then set again is no longer evicted ahead of older keys. (#35, fixes #28)
  • A cache restored with LoadFrom, LoadFromFile or LoadFromFileOrNew now evicts in the original insertion order. Snapshots are written oldest entry first. (#38, fixes #29)
  • SaveToFile and SaveToFileConcurrent flush the temporary file to disk before renaming it over the target. After a crash the target holds either the old snapshot or the complete new one, never a partial file. (#40, fixes #32)
  • Repeated Set and Delete calls on a cache below capacity no longer grow memory without bound. Two million Set/Delete pairs used to retain about 95 MiB. (#36, fixes #27)
  • New no longer allocates for maxEntries up front. Storage grows as entries are stored, so maxEntries works purely as a cap. An empty New(1_000_000) used to take about 108 MB. (#37, fixes #31)
  • Reset now releases the memory of the eviction queue, as documented. (#48, fixes #44)

Performance

  • Lock-free Get. Get no longer takes a shard lock or writes shared memory, and its hit and miss counters are spread across CPUs. Concurrent Gets of one key on 18 CPUs take 2.3 ns each instead of 112 ns. Inserting into a full cache is 44% faster. (#50, closes #45)
  • Eviction no longer copies the queue. The eviction queue is now a ring buffer. Set on a full cache of 4M entries takes about 240 ns instead of 1.7 µs. (#49, fixes #43)

Trade-offs

  • Updating an existing key now allocates (48 B for a string key and value) and takes 11–20 ns longer, which is about twice as long for short keys. (#50)
  • A Get miss takes about 5 ns longer. (#50)
  • Filling an empty cache is 7–23% slower, with occasional pauses while storage grows, since New no longer pays for it up front. (#37)
  • Saving 500k small entries takes about 1.85× as long, because entries are sorted into insertion order. (#38)
  • SaveToFile and SaveToFileConcurrent take longer because of the added disk flush. (#40)

Documentation

  • Fixed out-of-date mentions of snappy, map[K]V, ring buffers and "lock-free" atomic operations. The docs now say which operations serialize on which lock. (#42, closes #34)
  • The README benchmarks were rerun on an Apple M5 Pro with GOMAXPROCS=4. The previous numbers came from an AMD EPYC 7763, so the two sets can't be compared directly. (#50)

Internal

  • Removed an error channel in save that nothing ever sent on. (#41, closes #33)

Full changelog: v0.3.1...v0.4.0