Skip to content

08. PartitionStorage

ogoun edited this page Apr 23, 2026 · 1 revision

PartitionStorage

PartitionStorage is an embeddable, file-based key-value store. Data is laid out in partitions (subfolders on disk, driven by user-supplied metadata), with each partition storing one or more key-sorted files that can optionally carry a sparse index and a compression/merge step.

It is the substrate the Sleopok Engine is built on — but you can use it directly for any embedded KV scenario: append-heavy logs, tenant-partitioned caches, time-series rollups.

Core types

Store<TKey, TInput, TValue, TMeta>        // main entry point
StoreOptions<TKey, TInput, TValue, TMeta> // config
StoreSerializers<TKey, TInput, TValue>    // how keys/values/inputs are read & written
StoreCatalogPartition<TMeta>              // a subfolder rule
StoreFilePartition<TKey, TMeta>           // a file-name rule

Four generic parameters shape the store:

Parameter Meaning
TKey Record key.
TInput Value appended at write time (one per Store(key, value) call).
TValue Value after merge — typically TInput[] or a compressed blob.
TMeta Metadata that drives partition routing.

Minimal example

Index (tenant, userId) → events, compressing duplicate keys into one list:

public sealed class Meta
{
    public string Tenant { get; set; }
}

var options = new StoreOptions<long, string, string[], Meta>
{
    RootFolder = @"D:\store",
    KeyComparer = (a, b) => a.CompareTo(b),

    // one subfolder per tenant
    Partitions = new List<StoreCatalogPartition<Meta>>
    {
        new StoreCatalogPartition<Meta>("Tenant", m => m.Tenant),
    },

    // one file per key-hash bucket
    FilePartition = new StoreFilePartition<long, Meta>(
        name: "UserHash",
        fileNameExtractor: (userId, _) => (userId % 64).ToString()),

    // how to collapse duplicates
    MergeFunction = list => list.Distinct().OrderBy(x => x).ToArray(),

    Index = new IndexOptions
    {
        Enabled = true,
        StepType = IndexStepType.Step,
        StepValue = 32,
        EnableIndexInMemoryCachee = false,
    },

    ThreadSafeWriting = true,
};

var serializers = new StoreSerializers<long, string, string[]>(
    async (w, k) => await w.WriteLongAsync(k),
    async (w, v) => await w.WriteStringAsync(v),
    async (w, v) => await w.WriteStringArrayAsync(v),

    async r => new DeserializeResult<long>(true, await r.ReadLongAsync()),
    async r => new DeserializeResult<string>(true, await r.ReadStringAsync()),
    async r => new DeserializeResult<string[]>(true, await r.ReadStringArrayAsync()));

var store = new Store<long, string, string[], Meta>(options, serializers);

Writing

using (var builder = store.CreateBuilder(new Meta { Tenant = "acme" }))
{
    await builder.Store(userId: 42, "login");
    await builder.Store(userId: 42, "click:home");
    await builder.Store(userId: 99, "logout");

    builder.CompleteAdding();
    builder.Compress();                // runs MergeFunction across all keys
    await builder.RebuildIndex();      // if IndexOptions.Enabled == true
}

IStorePartitionBuilder<TKey, TInput, TValue> is IDisposable and thread-safe when ThreadSafeWriting is true.

Reading

using (var accessor = store.CreateAccessor(new Meta { Tenant = "acme" }))
{
    // exact key lookup
    SearchResult<string[]> sr = await accessor.Find(42);
    if (sr.Success) { /* sr.Value is the merged list for 42 */ }

    // iterate everything under this partition, in key order
    await foreach (var kvp in accessor.Iterate())
    {
        kvp.Deconstruct(out long key, out string[] value);
        // ...
    }

    int fileCount = accessor.CountDataFiles();  // diagnostics
}

Store.Bypass(meta) is a shortcut for iterating every record in a partition without the accessor lifetime.

Partitioning strategies

Two knobs decide how records are placed on disk:

1. Catalog partitions (subfolders)

Partitions = new List<StoreCatalogPartition<Meta>>
{
    new StoreCatalogPartition<Meta>("Tenant", m => m.Tenant),
    new StoreCatalogPartition<Meta>("Year",   m => m.Date.Year.ToString()),
},

Every partition is a nested subfolder. The example above creates D:\store\<tenant>\<year>\....

2. File partitions (buckets within a folder)

FilePartition = new StoreFilePartition<long, Meta>(
    "UserHash",
    (userId, meta) => (userId % 64).ToString());

The function computes a file name — records whose userId collide in the same bucket share the same file. Choosing a good bucket count matters: too few means hot files, too many means tiny file overhead.

Helper presets live in FilePartitionsPresets — e.g. ByDotNetHash(parts) uses StringHash.DotNetFullHash(key) % parts for stable string hashing.

Merging and compression

MergeFunction: Func<IEnumerable<TInput>, TValue> runs during Compress() — it collapses every record with the same key into a single TValue. Common shapes:

  • list => list.Distinct().ToArray() — deduplication.
  • list => list.OrderByDescending(x => x.Ts).Take(100).ToArray() — keep last N.
  • list => Compressor.Compress(list.ToArray()) — GZip the batch (see Sleopok).

Sparse index

When IndexOptions.Enabled = true the store builds a sparse in-file index:

Index = new IndexOptions
{
    Enabled = true,
    StepType = IndexStepType.Step,   // or AbsoluteCount
    StepValue = 32,
    EnableIndexInMemoryCachee = true,
}

Lookups jump to the nearest indexed position instead of scanning from the start. EnableIndexInMemoryCachee keeps the sparse index hot in RAM.

Concurrency

  • ThreadSafeWriting = true enables a lock inside the builder so multiple producers can Store(...) concurrently into the same partition file.
  • Readers are always safe to run in parallel with themselves.
  • A builder and an accessor for the same partition should not overlap in time — wait for Compress() / RebuildIndex() to finish before creating an accessor.

Memory-mapped accessor lifetime

Opened files are kept in a PhisicalFileAccessorCachee and closed after PhisicalFileAccessorExpirationPeriod (default 30 min) of inactivity. That keeps repeated small lookups fast without holding every file open forever.

Tips

  • Keep TValue small. It is the unit of a single Find — fetching MBs per key multiplies the cost of every lookup.
  • Pick catalog partitions so each subfolder holds at most a few hundred files. Filesystems hate huge flat directories.
  • Profile Compress() — it is the part that actually groups duplicate keys and is usually the longest step in an ingestion run.
  • Use a separate instance per TMeta family if your metas are not interchangeable — the Store<...> type itself is small.

Clone this wiki locally