garnet
Copilot instructions12k starsChanged 58 days agoMITView on GitHub
Garnet is a high-performance remote cache-store from Microsoft Research implementing the Redis RESP wire protocol in C#/.NET. It uses Tsavorite as its storage engine. Full developer docs: https://microsoft.github.io/garnet/docs/dev/onboarding Note: Some website docs may reference the older two-store architecture (separate main store and object store). This branch uses a unified single-store design — see the Architecture section below for the current model. Test ports are claimed automatically per test host, so several checkouts can run tests on one machine with no…
Trending
More talk lately.about the whole repository
Who's talking about microsoft/garnet
- A Hacker News story“Garnet – A new remote cache-store from Microsoft Research”Hacker News · Mar 19, 2024 · 370 points
- dotnet/aspnetcore“Redis distributed cache does not need to use Lua”GitHub · Mar 22, 2024 · 19 reactions
- @piss.beauty“C# doesn't get a ton of mindshare among devs lately, but it's wildly improved from its earlier versions, …”Bluesky · May 6, 2024 · 14 likes
- @brendan.fyi“"Garnet can work with existing Redis clients." MIT license Whoopsie doodle Redis github.com/microsoft/ga...”Bluesky · Mar 22, 2024 · 9 likes
- juicedata/juicefs“Add/test support for Microsoft Garnet”GitHub · Mar 22, 2024 · 5 reactions
The biggest 5 of 48 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 48
Talked about on GitHub, Bluesky and Hacker News (48 times).
On GitHub · 35
- Mar 22, 2024Redis distributed cache does not need to use Lua — dotnet/aspnetcore19 reactions · 5 comments
- Mar 22, 2024Add/test support for Microsoft Garnet — juicedata/juicefs5 reactions · 2 comments
- Nov 14, 2025Disk IO completions getting lost — dotnet/runtime4 reactions · 2 comments
- Apr 28, 2024Consider using Garnet — davidfowl/AspireWithRedis3 reactions · 1 comment
- Nov 21, 2024Propagate handshake failures to Handshake future — redis/lettuce2 reactions · 3 comments
30 more on GitHub
- May 10, 2024Potential corner-case error in optimized assembly — mmcloughlin/geohash2 reactions
- Mar 23, 2024Port the Unsafe.SizeOf Fixes from garnet — microsoft/FASTER2 reactions
- Mar 23, 2024use IsReferenceOrContainsReferences for .NET Standard 2.1+ and 6_0+ — microsoft/FASTER1 reaction · 1 comment
- Oct 5, 2026chore: bump garnet to 2.2.0 — glensouza/enterprise-homelab-template0 reactions
- Oct 2, 2026garnet 2.2.0 — Homebrew/homebrew-core0 reactions · 1 comment
- Oct 2, 2026chore(deps): update dependency microsoft/garnet to v2.2.0 — minhnbnt/aur0 reactions
- Sep 24, 2026chore(deps): update dependency microsoft.garnet to 2.2.0 — dailydevops/healthchecks0 reactions · 2 comments
- Sep 22, 2026garnet: 2.1.7 -> 2.1.8 — NixOS/nixpkgs0 reactions · 3 comments
- Sep 19, 2026chore: bump garnet to 2.1.8 — glensouza/enterprise-homelab-template0 reactions · 1 comment
- Sep 17, 2026garnet 2.1.8 — Homebrew/homebrew-core0 reactions · 2 comments
- Sep 17, 2026chore(deps): update dependency microsoft/garnet to v2.1.8 — minhnbnt/aur0 reactions · 1 comment
- Sep 12, 2026garnet: 2.1.5 -> 2.1.7 — NixOS/nixpkgs0 reactions · 4 comments
- Sep 11, 2026chore(deps): update dependency microsoft.garnet to 2.1.7 — dailydevops/healthchecks0 reactions · 1 comment
- Sep 11, 2026Bump Microsoft.Garnet from 2.1.5 to 2.1.7 — OrchardCoreContrib/OrchardCoreContrib0 reactions
- Sep 10, 2026chore(deps): update dependency microsoft/garnet to v2.1.7 — minhnbnt/aur0 reactions
- Sep 9, 2026garnet 2.1.7 — Homebrew/homebrew-core0 reactions · 1 comment
- Sep 9, 2026chore(deps): update dependency microsoft/garnet to v2.1.6 — minhnbnt/aur0 reactions · 1 comment
- Sep 9, 2026garnet 2.1.6 — Homebrew/homebrew-core0 reactions · 1 comment
- Sep 1, 2026garnet: 2.1.4 -> 2.1.5 — NixOS/nixpkgs0 reactions · 3 comments
- Aug 25, 2026garnet 2.1.5 — Homebrew/homebrew-core0 reactions · 1 comment
- Aug 12, 2026garnet 2.1.4 — Homebrew/homebrew-core0 reactions · 1 comment
- Aug 10, 2026garnet 2.1.3 — Homebrew/homebrew-core0 reactions · 1 comment
- Aug 5, 2026garnet 2.1.2 — Homebrew/homebrew-core0 reactions · 1 comment
- Jul 30, 2026garnet 2.1.1 — Homebrew/homebrew-core0 reactions · 1 comment
- Jul 28, 2026diskann_garnet nuget for macOS — microsoft/DiskANN0 reactions
- May 7, 2025failed to push some refs error when a bunch of charts updating — benchmark-action/github-action-benchmark0 reactions
- Sep 17, 2024Comparison with FASTER and Garnet? — StereoDB/StereoDB0 reactions · 2 comments
- Aug 12, 2024Support JSON schema for Garnet — SchemaStore/schemastore0 reactions
- Jul 5, 2024https://github.com/microsoft/garnet/blob/main/libs/host/Garnet.host.csproj — ignatandrei/PackageAnalyzer0 reactions
- Mar 26, 2024Maybe migrate from Redis to Garnet — nblockchain/FX0 reactions
On Bluesky · 11
- May 6, 2024C# doesn't get a ton of mindshare among devs lately, but it's wildly improved from its earlier versions, and you can achieve some pretty… — @piss.beauty14 likes and reposts · 3 replies
- Mar 22, 2024"Garnet can work with existing Redis clients." MIT license Whoopsie doodle Redis github.com/microsoft/ga... — @brendan.fyi9 likes and reposts
- Mar 30, 2024Garnet : un cache-store Open Source qui fonctionne avec les clients Redis existants... pour tous ceux qui se demandent pourquoi Microsoft… — @bearstech.com4 likes and reposts · 1 reply
- Mar 22, 2024right as redis changed their license from open source a free drop-in replacement got released github.com/microsoft/ga... — @domi.zip4 likes and reposts · 1 reply
- Mar 22, 2024githubはこれか。ちょうどRedisがアレな件もあるので乗り換え先として良いかも。ドキュメントにはマルチスレッド実装が故にMSETはnot atomicという記述を確認した。なるほどですね。 — @matsuu.bsky.social3 likes and reposts
6 more on Bluesky
- Mar 20, 2024A new player has entered the game. 😅 github.com/microsoft/ga... I'll test it in a few days. 😁 — @ferociousbyte.dev3 likes and reposts
- Mar 24, 2024github.com/microsoft/ga... — @tommis.fi2 likes and reposts
- Mar 23, 2024Bonjour et bon samedi ! Avec le changement de licence récent de Redis, les alternatives font surface. Ici Garnet de M$, sous licence MIT et… — @ponceto91.bsky.social1 likes and repost · 1 reply
- Mar 19, 2024github.com/microsof... GitHub - microsoft/garnet: Garnet is a remote cache-store from Microsoft Research that offers strong performance… — @technews4869.bsky.social1 likes and repost
- Mar 21, 2024💎 Hidden Gem! 💎 (1000+ new stars) 📦 microsoft / garnet ⭐ 3,020 (+1,118) 🗒 C# Garnet is a remote cache-store from Microsoft Research… — @github-trending.bsky.social0 likes and reposts · 1 reply
- Mar 19, 2024Garnet – A new remote cache-store from Microsoft Research Garnet - Microsoft Researchの新しいリモートキャッシュストア 🔺 279 💬 14 🔗 HN Post | Article — @hacker-news-jp.bsky.social0 likes and reposts · 1 reply
On Hacker News · 2
- Mar 19, 2024Garnet – A new remote cache-store from Microsoft Research370 points · 118 comments
- Sep 21, 2025Garnet – A remote cache-store from Microsoft Research4 points
In this repository2 other files it gives its agents.
- add-garnet-commandSkill
- pr-finalizeSkill
The file
Show its rules and text
We split this copilot-instructions.md into the rules it gives an agent
29 rules. About 0 are common, 3 are distinctive, and 26 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
26
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 37
Test ports are claimed automatically per test host, so several checkouts can run tests on one machine with no setup.
- Very specific: line 42
Test projects live under test/standalone/ and test/cluster/ — there is no bare test/Garnet.test.
- Very specific: line 46
Every test host claims its own TCP ports at startup, so several checkouts can run tests on one machine without coordinating.
- Distinctive: line 88
If the allocator cannot find a free block it fails before any test runs, reporting per-block why: leased by a running host, ports in use …
- Very specific: line 152
Define the command: Add enum value to RespCommand in libs/server/Resp/Parser/RespCommand.cs.
- Very specific: line 154
Declare the API method: Add method signature to IGarnetReadApi (read-only) or IGarnetApi (read-write) in libs/server/API/IGarnetApi.cs.
- Very specific: line 157
Implement storage logic: Add method to StorageSession.
- Very specific: line 158
String commands: Add to libs/server/Storage/Session/MainStore/MainStoreOps.cs.
- Very specific: line 159
Object (collection) commands: Add to libs/server/Storage/Session/ObjectStore/[ObjectName]Ops.cs.
- Very specific: line 162
Tests: Add tests using both StackExchange.Redis and LightClient where applicable.
- Very specific: line 163
Documentation: Update the appropriate markdown file under website/docs/commands/ and mark the command as supported in …
- Very specific: line 164
Command info metadata: Add the command to playground/CommandInfoUpdater/SupportedCommand.cs, then run the updater tool:
- Very specific: line 187
All C# files require this header (enforced by .editorconfig file_header_template):
- Very specific: line 199
Test base class: All test fixtures must inherit from TestBase (defined in test/standalone/Garnet.test/TestBase.cs).
- Very specific: line 200
Server lifecycle: Create in [SetUp] via TestUtils.CreateGarnetServer(TestUtils.MethodTestDir), call .Start(), then .Dispose() in [TearDown].
- Very specific: line 201
Teardown: Always call TestUtils.OnTearDown() (checks for leaked LightEpoch instances)
- Very specific: line 203
Namespace: Test files use Garnet.test namespace (even files in subdirectories like DiskANN/)
- Very specific: line 204
Clients in tests: Use StackExchange.Redis for high-level operations, LightClient for raw RESP protocol testing
- Very specific: line 240
Add property to Options class in libs/host/Configuration/Options.cs with [Option] attribute
- Very specific: line 241
Add default value in libs/host/defaults.conf
- Very specific: line 242
If needed in core code, add matching property to GarnetServerOptions (libs/server/Servers/GarnetServerOptions.cs) and map it in …
- Very specific: line 243
Add tests in test/Garnet.test/GarnetServerConfigTests.cs
- Distinctive: line 255
Keep comments tight, factual, and to the point: describe what the code does and why, in the present tense.
- Very specific: line 259
Use Span<T> and SpanByte extensively for zero-copy memory management — avoid allocations on hot paths
- Very specific: line 260
Use [MethodImpl(MethodImplOptions.AggressiveInlining)] for hot-path methods
- Very specific: line 261
Use [MethodImpl(MethodImplOptions.NoInlining)] for cold-path and exception-throwing methods
- Very specific: line 325
Page pointers: after OnPagesClosed → FreePage, pagePointers[idx] = 0.
- Very specific: line 345
When using SBB's CreateArgSlice, always RewindScratchBuffer after use — debug asserts enforce at most one outstanding slice.
- Very specific: line 347
When copying from IMemoryOwner<byte> (e.g., ObjectOutput.SpanByteAndMemory.Memory), always Dispose() after copying — do not leak pooled …
≈ “Common” is an estimate: at least 1 in 5 of the 1,644 Copilot instructions files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Garnet - Copilot Instructions
Garnet is a high-performance remote cache-store from Microsoft Research implementing the Redis RESP wire protocol in C#/.NET. It uses Tsavorite as its storage engine. Full developer docs: https://microsoft.github.io/garnet/docs/dev/onboarding
Note: Some website docs may reference the older two-store architecture (separate main store and object store). This branch uses a unified single-store design — see the Architecture section below for the current model.
Build, Test, and Lint
# Build the entire solution
dotnet build
# Run all Garnet tests
dotnet test test/standalone/Garnet.test -f net10.0 -c Debug -l "console;verbosity=detailed"
# Run all cluster tests
dotnet test test/cluster/Garnet.test.cluster -f net10.0 -c Debug -l "console;verbosity=detailed"
# Run a single test by fully qualified name
dotnet test test/standalone/Garnet.test -f net10.0 -c Debug --filter "FullyQualifiedName~RespTests.PingTest"
# Run all tests in a single test class
dotnet test test/standalone/Garnet.test -f net10.0 -c Debug --filter "FullyQualifiedName~RespTests"
# Build and test Tsavorite independently (has its own solution)
dotnet build libs/storage/Tsavorite/cs/test/Tsavorite.test.csproj
dotnet test libs/storage/Tsavorite/cs/test/Tsavorite.test.csproj -f net10.0 -c Debug -l "console;verbosity=detailed"
# Check formatting (CI enforces this)
dotnet format Garnet.slnx --verify-no-changes
dotnet format libs/storage/Tsavorite/cs/Tsavorite.slnx --verify-no-changes
# Run the server locally (from repo root)
cd main/GarnetServer && dotnet run -c Debug -f net10.0 -- --logger-level Trace -m 4g -i 64mTest ports are claimed automatically per test host, so several checkouts can run tests on one machine with no setup; see Test ports.
Target frameworks are net8.0 and net10.0. CI runs tests on both, in Debug and Release, on Ubuntu and Windows.
Test projects live under test/standalone/ and test/cluster/ — there is no bare test/Garnet.test.
Test ports
Every test host claims its own TCP ports at startup, so several checkouts can run tests on one machine without
coordinating. Nothing needs to be set: dotnet test works as-is, and the same mechanism runs in CI.
Each test project reserves one aligned block of 32 ports for the life of the process. Standalone projects use
the first two (TestUtils.TestPort and TestUtils.AlternateTestPort); cluster projects use a contiguous run,
since node n binds ClusterTestContext.Port + n. The reservation is made from the project's
TestProjectSetup, which calls TestUtils.ReserveTestPorts or ClusterTestContext.ReservePorts. Adding a test
project needs no central registration - the allocator identifies a project by its assembly name.
Two properties make this safe, and both matter:
- Ports come from
[16384, 32768). Linux assigns outbound connections from 32768-60999 by default (net.ipv4.ip_local_port_range), and Windows and macOS from 49152-65535. A listening port inside those ranges can be taken by the kernel between the moment it is observed free and the moment the server binds it. No amount of probing closes that window, so the allocatable range stays below all of them. The range also stays above the crowded region below 16384, which holds both ports a Garnet developer is likely to be running (6379 Redis, 5432, 11211, 8080) and ports the suite itself uses (10000-10002 Azurite). - A block is leased by an exclusively locked file in the temp directory for the life of the test host. That is what stops two test hosts choosing the same block. The OS releases the lock on exit, crash, or kill, so a block frees itself without cleanup. The lease is checked first and the ports are then probed, because a service unrelated to the suite - or a server stranded by a killed run - holds ports while holding no lease.
Ports 30000-30999 are reserved for test/docker-tests/validate_docker_images.py, which allocates container
ports from its own fixed base and can run alongside the managed suite. TestPortAllocatorTests reads that base
out of the Python file, so moving either side without the other fails as a test rather than as an intermittent
container start failure.
GARNET_TEST_PORT_BASE pins an explicit base port, for reproducing a failure on a known port or for a host
whose firewall only opens a fixed range. The pinned ports are still leased and probed, so pinning cannot
silently reintroduce a collision.
When a port conflict happens anyway
A failed bind reports the endpoint and the operating system's reason, and TestUtils.OnTearDown adds the
allocation context. Because reserved ports are leased, were probed free at startup, and sit below every
ephemeral range, an occupant can be neither the kernel nor another Garnet test host - so the message says
plainly that it is software outside the suite, not a defect in Garnet or in the test.
Find the occupant with Get-NetTCPConnection -LocalPort <port> on Windows or ss -ltnp on Linux, and stop it
by process id. Never terminate by name (Stop-Process -Name dotnet, taskkill /IM testhost.exe): that kills
other checkouts' test hosts and builds, which surfaces as a test host vanishing with no .NET fault event.
If the allocator cannot find a free block it fails before any test runs, reporting per-block why: leased by a running host, ports in use with no lease, or reserved for the Docker harness. NUnit then reports every test in the assembly as errored, zero tests run, and the process exits non-zero.
One further caution when sharing a machine: check test output for error CS before trusting a result. With
--no-build, and when a compile error surfaces in a project that is not rebuilt, dotnet test runs the
previously built assembly and can report a pass for code that never compiled.
Architecture
Unified Single-Store Design
Garnet uses a single Tsavorite key-value store instance (TsavoriteKV<StoreFunctions, StoreAllocator>) that holds both raw strings and complex objects. The store is accessed through three different context types, each with its own input/output types and session functions:
| Context | Input/Output Types | Session Functions | Used For |
| String context | StringInput / StringOutput | MainSessionFunctions | Raw string commands (GET, SET, APPEND, INCR, etc.) |
| Object context | ObjectInput / ObjectOutput | ObjectSessionFunctions | Collection commands (HSET, LPUSH, ZADD, SADD, etc.) |
| Unified context | UnifiedInput / UnifiedOutput | UnifiedSessionFunctions | Type-agnostic commands (EXISTS, DELETE, TYPE, TTL, EXPIRE, RENAME, etc.) |
All three contexts operate on the same underlying store. At the storage level, each record's RecordInfo has a ValueIsObject bit that indicates whether the value is a raw string (inline bytes) or a heap object reference, enabling the unified store to differentiate between the two value types. The GarnetApi struct is generic over all three context types:
public partial struct GarnetApi<TStringContext, TObjectContext, TUnifiedContext>Two concrete instantiations are used: BasicGarnetApi (normal operations) and TransactionalGarnetApi (within transactions). Type aliases for all context variants are defined in libs/GlobalUsings.cs.
The single store is held by GarnetDatabase (libs/server/GarnetDatabase.cs) and managed by StoreWrapper (libs/server/StoreWrapper.cs). Each record carries a ValueIsObject bit in its RecordInfo header to distinguish raw string values from serialized object values.
Storage layer organization
Each context type has parallel directory structures:
- Functions (Tsavorite callbacks for RMW, Read, Upsert, Delete):
libs/server/Storage/Functions/MainStore/— string operationslibs/server/Storage/Functions/ObjectStore/— collection operationslibs/server/Storage/Functions/UnifiedStore/— type-agnostic operations
- Session ops (StorageSession methods wrapping Tsavorite API):
libs/server/Storage/Session/MainStore/— string ops (MainStoreOps.cs, BitmapOps.cs, HyperLogLogOps.cs)libs/server/Storage/Session/ObjectStore/— collection ops ([ObjectName]Ops.cs)libs/server/Storage/Session/UnifiedStore/— unified ops (UnifiedStoreOps.cs)
- Object implementations:
libs/server/Objects/[ObjectName]/— per-type logic (Hash, List, Set, SortedSet, SortedSetGeo)
Key Layers
- Network/Session (
libs/common/Networking/,libs/server/Sessions/) — Shared-memory network design where TLS and storage ops run on IO completion threads.GarnetServerTcpaccepts connections, createsServerTcpNetworkHandlerper client.GarnetProvidercreatesRespServerSessioninstances to handle RESP messages. - RESP Command Processing (
libs/server/Resp/) — Commands are defined asRespCommandenum values and dispatched via switch expressions inProcessBasicCommands/ProcessArrayCommands. TheRespServerSessionclass is split across multiple partial.csfiles organized by command category. - Storage API (
libs/server/API/) — Narrow-waist API (IGarnetApiinheritsIGarnetReadApi+IGarnetAdvancedApi) with read, upsert, delete, and atomic read-modify-write operations. Command handlers are generic overTGarnetApifor testability.StorageSessionwraps Tsavorite API calls. API methods for string, object, and unified commands are split acrossGarnetApi.cs,GarnetApiObjectCommands.cs, andGarnetApiUnifiedCommands.cs. - Tsavorite Engine (
libs/storage/Tsavorite/cs/src/core/) — Has its own solution (Tsavorite.slnx) and test project. Provides concurrent key-value storage with checkpointing, tiered storage, recovery, and epoch-based memory reclamation. Relies heavily onSpan<T>andSpanBytefor zero-copy memory management. - Cluster (
libs/cluster/) — Sharding, replication, gossip protocol, key migration. Interface defined inlibs/server/Cluster/IClusterProvider.cs, implementation inlibs/cluster/Server/. - Database Management (
libs/server/Databases/) — Factory pattern withSingleDatabaseManagerandMultiDatabaseManagerimplementations behindIDatabaseManager. Multi-database only available when cluster mode is off. EachRespServerSessionmanages a map ofGarnetDatabaseSessioninstances (one per database index).
Type Aliases
The codebase uses using aliases extensively for complex generic store types. libs/GlobalUsings.cs defines the key aliases: BasicGarnetApi, TransactionalGarnetApi, StringBasicContext, ObjectBasicContext, UnifiedBasicContext, StoreAllocator, and their transactional variants. See also the top of RespServerSession.cs and StoreWrapper.cs.
Adding a New RESP Command
Full guide: https://microsoft.github.io/garnet/docs/dev/garnet-api
Steps for a new built-in command:
- Define the command: Add enum value to
RespCommandinlibs/server/Resp/Parser/RespCommand.cs. For object commands (List, SortedSet, Hash, Set), also add a value to the[ObjectName]Operationenum inlibs/server/Objects/[ObjectName]/[ObjectName]Object.cs. - Add parsing logic: In
libs/server/Resp/Parser/RespCommandHashLookupData.cs, add an entry toPopulatePrimaryTable()(e.g.,Add("MYNEWCMD", RespCommand.MYNEWCMD)). For commands with subcommands, sethasSub: trueand add a subcommand table. The hash table provides O(1) lookup for all command name lengths. - Declare the API method: Add method signature to
IGarnetReadApi(read-only) orIGarnetApi(read-write) inlibs/server/API/IGarnetApi.cs. - Implement the network handler: Add a method to
RespServerSession(the class is split across ~22 partial.csfiles — object commands go inlibs/server/Resp/Objects/[ObjectName]Commands.cs, others inlibs/server/Resp/BasicCommands.cs,ArrayCommands.cs,AdminCommands.cs,KeyAdminCommands.cs, etc.). The handler parses arguments from the network buffer viaparseState.GetArgSliceByRef(i)(returnsref PinnedSpanByte), calls the storage API, and writes the RESP response usingRespWriteUtilshelper methods, then callsSendAndReset()to flush the response buffer. - Add dispatch route: In
libs/server/Resp/RespServerSession.cs, add a case toProcessBasicCommandsorProcessArrayCommandscalling the handler from step 4. - Implement storage logic: Add method to
StorageSession. Choose the appropriate context based on the command type:- String commands: Add to
libs/server/Storage/Session/MainStore/MainStoreOps.cs. Call Tsavorite'sReadorRMWvia the string context. For RMW, implement init/update logic inlibs/server/Storage/Functions/MainStore/RMWMethods.cs. - Object (collection) commands: Add to
libs/server/Storage/Session/ObjectStore/[ObjectName]Ops.cs. CallReadObjectStoreOperationorRMWObjectStoreOperationvia the object context, then implement the case inlibs/server/Objects/[ObjectName]/[ObjectName]ObjectImpl.cs. - Type-agnostic commands (EXISTS, DELETE, TTL, EXPIRE, TYPE, etc.): Add to
libs/server/Storage/Session/UnifiedStore/UnifiedStoreOps.cs. Use the unified context. Implement callbacks inlibs/server/Storage/Functions/UnifiedStore/RMWMethods.cs.
- String commands: Add to
- Transaction support: For standard commands, define
KeySpecsin the command's metadata — the framework automatically handles key locking viaTxnKeyManager.LockKeys(). For custom multi-key operations, manually calltxnManager.SaveKeyEntryToLock(key, lockType)inlibs/server/Transaction/TxnKeyManager.cs; the key is aPinnedSpanBytein the unified key-space, so object-vs-string handling is managed internally by the transaction layer. - Tests: Add tests using both
StackExchange.RedisandLightClientwhere applicable. Object command tests go intest/Garnet.test/Resp[ObjectName]Tests.cs, others intest/Garnet.test/RespTests.csor similar. - Documentation: Update the appropriate markdown file under
website/docs/commands/and mark the command as supported inwebsite/docs/commands/api-compatibility.md. - Command info metadata: Add the command to
playground/CommandInfoUpdater/SupportedCommand.cs, then run the updater tool:cd playground/CommandInfoUpdater dotnet run -- --output ../../libs/resources
Tip: Write a basic test calling the new command first, then implement missing logic as you debug.
Custom Extensions
Four extensibility points, all in C#. See https://microsoft.github.io/garnet/docs/dev/custom-commands
CustomRawStringFunctions— Custom operations on raw strings (example:main/GarnetServer/Extensions/DeleteIfMatch.cs)CustomObjectBase+CustomObjectFactory— Custom data types for the object store (example:main/GarnetServer/Extensions/MyDictObject.cs)CustomTransactionProcedure— Server-side multi-key transactions (example:main/GarnetServer/Extensions/ReadWriteTxn.cs)CustomProcedure— Non-transactional server-side stored procedures (example:main/GarnetServer/Extensions/Sum.cs)
Register server-side via server.Register (a RegisterApi instance on GarnetServer) with .NewCommand(), .NewTransactionProc(), .NewProcedure(), or .NewType(). Client-side registration uses the REGISTERCS admin command with assemblies on the server.
Key Conventions
File Headers
All C# files require this header (enforced by .editorconfig file_header_template):
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.This same header is used throughout the entire codebase, including Tsavorite files.
Test Structure
- Framework: NUnit with
[TestFixture],[Test],[SetUp],[TearDown] - Test base class: All test fixtures must inherit from
TestBase(defined intest/standalone/Garnet.test/TestBase.cs). This tracks currently running tests for diagnostics. - Server lifecycle: Create in
[SetUp]viaTestUtils.CreateGarnetServer(TestUtils.MethodTestDir), call.Start(), then.Dispose()in[TearDown]. Common optional parameters includeenableAOF,lowMemory,enableTLS,enableCluster,tryRecover,disableObjects,useAcl, anddefaultPassword. - Teardown: Always call
TestUtils.OnTearDown()(checks for leakedLightEpochinstances) - Test directory cleanup:
TestUtils.DeleteDirectory(TestUtils.MethodTestDir, wait: true)at the start of[SetUp] - Namespace: Test files use
Garnet.testnamespace (even files in subdirectories likeDiskANN/) - Clients in tests: Use
StackExchange.Redisfor high-level operations,LightClientfor raw RESP protocol testing
[TestFixture]
public class MyTests : TestBase
{
GarnetServer server;
[SetUp]
public void Setup()
{
TestUtils.DeleteDirectory(TestUtils.MethodTestDir, wait: true);
server = TestUtils.CreateGarnetServer(TestUtils.MethodTestDir);
server.Start();
}
[TearDown]
public void TearDown()
{
server.Dispose();
TestUtils.OnTearDown();
}
[Test]
public void MyTest()
{
using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig());
var db = redis.GetDatabase(0);
// ... test using StackExchange.Redis
}
}Adding Configuration Settings
To add a new Garnet server setting:
- Add property to
Optionsclass inlibs/host/Configuration/Options.cswith[Option]attribute - Add default value in
libs/host/defaults.conf - If needed in core code, add matching property to
GarnetServerOptions(libs/server/Servers/GarnetServerOptions.cs) and map it inOptions.GetServerOptions() - Add tests in
test/Garnet.test/GarnetServerConfigTests.cs
Coding Style
- 4-space indentation, Allman braces (opening brace on new line)
varpreferred when type is apparentunsafeandAllowUnsafeBlocksenabled globally- Private/internal fields: camelCase; constants and statics: PascalCase
TreatWarningsAsErrorsis enabled — all warnings must be resolved- Central package version management via
Directory.Packages.props - XML doc comments (
/// <summary>) are strongly recommended on public methods, with<param>tags for each parameter; analyzer rules for missing docs are currently configured as suggestions (see.editorconfig) - Comment format:
// Comment starting with a capital letter(one space after//) - Keep comments tight, factual, and to the point: describe what the code does and why, in the present tense. Don't narrate history, reference issues/PRs, or describe problems, bugs, or prior approaches.
Performance Conventions
- Use
Span<T>andSpanByteextensively for zero-copy memory management — avoid allocations on hot paths - Use
[MethodImpl(MethodImplOptions.AggressiveInlining)]for hot-path methods - Use
[MethodImpl(MethodImplOptions.NoInlining)]for cold-path and exception-throwing methods - Tsavorite uses
LightEpochfor epoch-based safe memory reclamation — acquire epoch protection before store operations, release after LightEpochinstances track ownership — only dispose if owned- In parallel tests, share a
LightEpochinstance acrossGarnetClientinstances
Epoch Protection and Log Address Invariants
Tsavorite uses epoch-based memory reclamation (LightEpoch) so writers can publish new values and reclaim old memory only after every reader has moved past it. Any change to the allocator, recovery, scan iterators, transient locking, or callbacks fired from the drain list must respect the rules below.
Key files: libs/storage/Tsavorite/cs/src/core/Epochs/LightEpoch.cs, libs/storage/Tsavorite/cs/src/core/Allocator/AllocatorBase.cs, libs/storage/Tsavorite/cs/src/core/ClientSession/ClientSession.cs.
Epoch protection model (LightEpoch)
- Each thread acquires a per-instance entry via
epoch.Resume()(callsAcquire) and releases it viaepoch.Suspend()(callsRelease). Inside the protected region, the thread'slocalCurrentEpochis advanced on everyProtectAndDrain()call and on entry. Resume()is non-reentrant —Acquireasserts if the thread is already protected on this instance. UseResumeIfNotProtected()(returnstrueif it acquired) when code may be entered under an existing hold; pair with a matchingSuspend()only on the path that took it.BasicContext.{RMW, Upsert, Read, Delete}wrap the call inUnsafeResumeThread()/UnsafeSuspendThread()(inClientSession) via try/finally. Custom code that callsepoch.ProtectAndDrain()(e.g., spin-waiters inEpochOperations.SpinWaitUntilClosed/SpinWaitUntilRecordIsClosed,TransientLocking.LockForScan) must already hold the epoch — theDebug.Assert(entry > 0, "Trying to refresh unacquired epoch")inLightEpoch.ProtectAndDrainfires otherwise.BumpCurrentEpoch(Action)increments the global epoch and queuesActionagainst the prior epoch. The action fires on whatever thread next observes that epoch as safe-to-reclaim — typically insideProtectAndDrain→Drain. Therefore actions must be thread-agnostic (no thread-affine state) and safe to fire synchronously from the bumping thread itself:BumpCurrentEpoch(Action)callsProtectAndDraininternally and may execute the action it just queued.
Log address layout and invariants
The seven log addresses on AllocatorBase advance monotonically and obey:
BeginAddress <= ClosedUntilAddress <= SafeHeadAddress <= HeadAddress
<= FlushedUntilAddress
<= SafeReadOnlyAddress <= ReadOnlyAddress <= TailAddress| Address | Meaning |
BeginAddress | Lowest valid address. Advancing it logically retires older addresses but does not delete on-disk files by itself; physical truncation only happens when a ShiftBeginAddress caller passes truncateLog: true (typically a checkpoint commit), and even then the device may defer file removal. |
ClosedUntilAddress | Highest address whose page buffer has been freed (pagePointers[idx] = 0). |
SafeHeadAddress | High-water set by OnPagesClosed before freeing — readers see it lead ClosedUntilAddress. |
HeadAddress | Lowest in-memory address. May advance while you hold the epoch, but any address that was >= HeadAddress at any point during your protected region cannot be evicted until you Suspend. Capped at FlushedUntilAddress — eviction never gets ahead of disk durability. |
FlushedUntilAddress | All bytes below have been written to disk. Updated by flush completion callbacks invoked from AsyncFlushPagesForReadOnly. Lags SafeReadOnlyAddress (a page is only flushed once it has become safely read-only). |
SafeReadOnlyAddress | Below this, no writer can be in-place mutating. Set by OnPagesMarkedReadOnly after writers have drained; same call also kicks off the flush that will later advance FlushedUntilAddress. |
ReadOnlyAddress | Maximum address of the immutable region. Records below are flushed/in-flush. |
TailAddress | Next address to allocate; published via the PageOffset CAS in HandlePageOverflow. |
Cascade pattern: publish → epoch barrier → post-drain action
Address advancement uses a publish → bump → action cascade so that the post-barrier work runs only after every prior holder has observed the new value:
- Publish the new address into the visible field via
MonotonicUpdate. BumpCurrentEpoch(Action)queues the post-barrier work against the prior epoch; it fires once every thread that observed the old value has eitherSuspended orProtectAndDrained.- The action does the work that requires "all prior holders have moved past": flush pages, advance the
Safe*companion, close pages, free buffers, truncate disk segments.
The two cascades you encounter on the runtime hot path:
- Read-only / flush cycle —
ShiftReadOnlyAddress(newRO)publishesReadOnlyAddress, thenBumpCurrentEpoch(OnPagesMarkedReadOnly). The action advancesSafeReadOnlyAddressand issuesAsyncFlushPagesForReadOnly; flush completion later advancesFlushedUntilAddressviaFlushCallback. Triggered byPageAlignedShiftReadOnlyAddresswhenever the tail moves far enough past the read-only region. - Eviction / close cycle —
ShiftHeadAddress(desiredHA)publishesHeadAddress, thenBumpCurrentEpoch(OnPagesClosed). The action advancesSafeHeadAddressandClosedUntilAddress, and frees page buffers via the per-allocatorFreePage(defined inSpanByteAllocatorImpl/ObjectAllocatorImpl). Triggered whenFlushedUntilAddressmoves pastHeadAddress + (some delta), or explicitly viaShiftHeadAddressToBlocking.
Other cascades:
ShiftBeginAddress(newBA, truncateLog)— publishesBeginAddress(and cascades throughShiftReadOnlyAddress+ShiftHeadAddressif needed). WhentruncateLog: true, also bumps withTruncateUntilAddressto drop on-disk segments below the new begin; whenfalse(the common case) on-disk segments are left in place to be reclaimed at the next checkpoint commit. Disk file removal itself is asynchronous — even afterTruncateUntilAddressreturns, the device may defer the actual unlink.ShiftReadOnlyAddressWithWait(newRO, wait)— convenience wrapper that usesResumeIfNotProtected/Suspendto launch the shift and (optionally) blocks the caller onFlushedUntilAddress < newRO.
Rules when changing allocator/iterator/callback code
- Holding the epoch implies stability: an address observed
>= HeadAddressduring the protected region cannot be evicted beforeSuspend(). Re-acquire after suspend and re-validate. SuspendandResumemust be balanced on every code path. The only suspend inside the basic op path is theALLOCATE_FAILEDretry inHandleRetryStatus, balanced via try/finally.- Drain-list actions run on arbitrary threads that hold the epoch. Do not capture thread-static state; do not call code that asserts on a specific thread.
- Multi-phase mutations that need to advance several addresses with barriers between them should use one
BumpCurrentEpoch(Action)per phase with aManualResetEventSlimto wait. Drop the prior epoch before waiting on the MRE — otherwise the drain list cannot make progress (the action you queued cannot fire while you hold the epoch it is gating on). Re-acquire to issue the next bump.AllocatorBase.Resetis an example: phase 1 publishesReadOnlyAddressand waits for writers to drain before advancingSafeReadOnlyAddress/FlushedUntilAddress; phase 2 publishesHeadAddressand waits for readers to drain before closing/freeing pages. - Address publication ordering: when one operation advances multiple addresses, advance the more permissive ones (
HeadAddress,ReadOnlyAddress) before the more restrictive ones (BeginAddress). The full invariantBeginAddress <= ClosedUntilAddress <= SafeHeadAddress <= HeadAddress <= FlushedUntilAddress <= SafeReadOnlyAddress <= ReadOnlyAddress <= TailAddressmust hold throughout, and stale readers caching the older value will route through safer paths (e.g., disk-frame branch inLoadPageIfNeededrather than dereferencing freedpagePointers).AllocatorBase.ResetpublishesBeginAddresslast for this reason — an iterator with a stalenextAddressthen routes through the disk-frame path instead of the in-memory page that has just been freed. - Page pointers: after
OnPagesClosed→FreePage,pagePointers[idx] = 0. Iterators must not dereference a page pointer outside the epoch protection that observedaddr >= HeadAddress. - Scan iterators and
BufferAndLoad:ScanIteratorBase.BufferAndLoadmay internally callBumpCurrentEpoch,ProtectAndDrain, orSuspend+Resumeon IO, any of which advances the iterator thread'slocalCurrentEpochand may synchronously fire deferred drain-list actions. Reads stay safe because the IO frame is iterator-owned (allocated in the iterator's constructor) andheadAddressadvances monotonically —LoadPageIfNeededonly routes a record to the in-log path when it was>= HeadAddressat the time of sampling, so the snapshot's routing decision is always conservative.
Tests that exercise these paths
BasicLockTests.FunctionsLockTest(inlibs/storage/Tsavorite/cs/test/BasicLockTests.cs) — multi-threaded RMW/Upsert under contention; exercises Resume/Suspend balance andProtectAndDrain.- Cluster checkpoint/flush tests under
test/Garnet.test.cluster/— exercise the full address cascade with live clients.
Scratch Buffer Conventions
StorageSession has two scratch buffer types — use the right one:
ScratchBufferBuilder(SBB) — Single contiguous buffer for temporary workspace. All data is laid out sequentially in one buffer. On expansion, the previous data is copied into a new larger buffer and the old buffer is freed — any existing pointers into the old buffer become invalid. Use for building command inputs, Lua serialization, or any data that is consumed immediately and then rewound. Do not returnPinnedSpanBytefrom SBB to callers — it may be invalidated by subsequent allocations. Always rewind after use. Debug builds enforce single-outstanding-slice discipline via asserts.- Key APIs:
CreateArgSlice(returnsPinnedSpanByte, must rewind),CreateArgSliceAsOffset(returns(Offset, Length), safe for multi-alloc since offsets survive reallocation),ViewRemainingArgSlice/ViewFullArgSlice(immediate-use views, do not store),MoveOffset,Reset,RewindScratchBuffer.
- Key APIs:
ScratchBufferAllocator(SBA) — Maintains a collection of fragmented pinned buffers (viaGC.AllocateArray(_, true)). When the current buffer fills, a new one is allocated and the old buffer is kept rooted in a stack — so previously returnedPinnedSpanBytevalues remain valid. Use forPinnedSpanBytevalues returned viaoutparameters orIGarnetApithat callers retain across multiple API calls. Reset between batches.- Key APIs:
CreateArgSlice,ViewRemainingArgSlice,Reset.
- Key APIs:
Rules:
- Any
StorageSessionorIGarnetApimethod returningPinnedSpanByteviaoutmust use SBA, not SBB. - When using SBB's
CreateArgSlice, alwaysRewindScratchBufferafter use — debug asserts enforce at most one outstanding slice. - For multiple allocations without rewind, use
CreateArgSliceAsOffset(returns offsets that survive reallocation). - When copying from
IMemoryOwner<byte>(e.g.,ObjectOutput.SpanByteAndMemory.Memory), alwaysDispose()after copying — do not leak pooled buffers. ViewFullArgSliceandViewRemainingArgSlicereturn immediate-use views — do not store or return them.
Releasing a New Version
To update the version and make a new release, increment the VersionPrefix in Version.props at the repo root and submit a PR with that change.
PR Protocol
- Do not create an issue unless asked to do so. If such a request is made, create the issue with a clear and complete but concise description, assign it to the current user, and link the PR to the issue in the development section. Once an Issue has been created, do not update it until the PR is opened unless asked; when the PR is opened, update the Issue (again, completely but concisely) with any necessary changes. a. Similarly, do not create a PR until asked. A PR may be created without an underlying Issue; the PR must completely and concisely state the problem. Once a PR has been created, update its description (again, completely but concisely) on subsequent commits with any necessary changes.
- It is acceptable and encouraged to consolidate smaller changes into a single larger PR for reviewer convenience and reducing bookkeeping and process, as long as the PR description clearly outlines the different fixes or improvements being made in the work.
- Branch naming:
<username>/branch-name - Include unit tests (see Test Structure above)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

