Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -352,8 +352,8 @@ sealed class QuerySettings
// Bloom filters are not settings: they keep the engine's defaults.
sealed class StoreSettings
{
[Setting("Write-ahead log", Help = "Async compressed is ZoneTree's default.")]
public WriteAheadLogMode WriteAheadLogMode { get; set; } = WriteAheadLogMode.AsyncCompressed;
[Setting("Write-ahead log", Help = "Async private is ZoneTree's default.")]
public WriteAheadLogMode WriteAheadLogMode { get; set; } = WriteAheadLogMode.AsyncPrivate;

[Setting("Mutable segment size", Unit = "records", Min = 1000, Max = 100000000, EmptyLabel = "ZoneTree default")]
public int? MutableSegmentMaxItemCount { get; set; }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>disable</Nullable>
<IsPackable>false</IsPackable>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,7 @@ Merge this logging section into the host's `appsettings.json`, or the environmen
For a standalone engine, set its logger before opening it:

```csharp
options.Storage.Logger = new ZoneTree.Logger.ConsoleLogger
{
LogLevel = ZoneTree.Logger.LogLevel.Info,
};
options.Storage.Logger = new ZoneTree.Logging.ConsoleLogger(ZoneTree.Logging.ZoneTreeLogLevel.Info);
```

An engine opened outside dependency injection in an ASP.NET Core host can also use the integration's `UseLogger` extension to forward engine and storage messages to a host logger.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ Completed coverage is recorded for reuse after reopening. After interrupted writ

Interrupted backfills resume from saved checkpoints. Copy backfills checkpoint every 100,000 input records and at partition boundaries. Historical joint-rollup reconstruction also preserves active sessions and replays absolute contributions to avoid counting the same chunk twice.

Recovery follows the configured write-ahead log (WAL) mode. The default `AsyncCompressed` mode can lose recent writes in a crash, including index copies or reconstructed aggregate contributions. Raw events can remain stored while their reconstructed aggregates miss those contributions. Use synchronous WAL for the stores involved when checkpoint recovery must retain every completed write.
Recovery follows the configured write-ahead log (WAL) mode. The default `AsyncPrivate` mode can lose recent writes in a crash, including index copies or reconstructed aggregate contributions. Raw events can remain stored while their reconstructed aggregates miss those contributions. Use `Private` WAL for the stores involved when checkpoint recovery must retain every completed write after a process crash.

Information logs report reuse, repair, or rebuild decisions, checkpoint progress, resumed counts, duration, and throughput. Configuration changes, missing retained partitions, and stores configured without a write-ahead log can still require a full rebuild.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ Track the attribute as an event dimension, such as an experiment variant. Later
| `Sessions` | `StoreOptions` | ZoneTree settings of the active session store. By default the mutable segment holds 50,000 sessions. |
| `WriteAheadLogDirectory` | `string` | A separate root directory for write-ahead logs, for example on a faster disk. Each store keeps its log under the same relative path as its data. Null (the default) keeps logs next to the data. It is persisted when the data directory is created and cannot be changed afterwards, because unflushed records live in the log. |
| `PartitionIdleTimeout` | `TimeSpan` | Partitions that were not used for this long are closed. Default is 10 minutes. |
| `Logger` | `ILogger` | The logger used by the engine and its ZoneTree stores. Default is a console logger at warning level. |
| `Logger` | `IZoneTreeLogger` | The logger used by the engine and its ZoneTree stores. Default is a console logger at warning level. |

## PartitioningOptions

Expand All @@ -224,15 +224,17 @@ Track the attribute as an event dimension, such as an experiment variant. Later

| Setting | Type | Behavior and default |
| --- | --- | --- |
| `WriteAheadLogMode` | `WriteAheadLogMode` | The write-ahead-log mode. Default is `WriteAheadLogMode.AsyncCompressed`. |
| `WriteAheadLogMode` | `WriteAheadLogMode` | The write-ahead-log mode. Default is `WriteAheadLogMode.AsyncPrivate`. |
| `MutableSegmentMaxItemCount` | `int?` | How many recent records are held in the mutable (in-memory) segment before it moves toward disk. |
| `DiskSegmentMaxItemCount` | `int?` | How many records a disk segment holds before merges start a new one. |
| `EnableSingleSegmentGarbageCollection` | `bool?` | Removes deleted records on load when a tree consists of its mutable segment only. |
| `AllowUnsafeOptionValues` | `bool` | Lets ZoneTree accept option values outside its recommended ranges. |
| `ConfigureWriteAheadLog` | `Action<WriteAheadLogOptions>` | Tunes the write-ahead log, for example compression or incremental backup. Runs after `WriteAheadLogMode` is applied. |
| `ConfigureWriteAheadLog` | `Action<WriteAheadLogOptions>` | Tunes the write-ahead log, for example compression or sync intervals. Runs after `WriteAheadLogMode` is applied. |
| `ConfigureDiskSegments` | `Action<DiskSegmentOptions>` | Tunes disk segments, for example the segment mode, compression or caches. |
| `ConfigureMaintainer` | `Action<IMaintainer>` | Tunes the maintainer of every tree, for example merge thresholds or block cache cleanup. |

ZoneTree 2.2.0 requires storage format 2.1.10 or newer. Before upgrading an existing installation, open every older tree once using ZoneTree 2.1.10 with `EnableZstdMigration()`, then close it before starting Analytics with 2.2.0. Include historical partitions and the dashboard system store. Keep each tree's serializers and WAL location, and configure Zstd or no compression and a WAL mode other than `Sync` for the migration. Follow the [ZoneTree storage upgrade guide](https://zonetree.dev/docs/storage/compression/#upgrade-from-a-version-before-2110).

## WebOptions

| Setting | Type | Behavior and default |
Expand Down
2 changes: 1 addition & 1 deletion examples/MinimalHost/MinimalHost.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>disable</Nullable>
<IsPackable>false</IsPackable>
Expand Down
6 changes: 4 additions & 2 deletions internal-docs/storage-format.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ There are two layers to the persisted format:
| Analytics records | ZoneTree.Analytics | Directory routing, keys, event payloads, rollup and session serializers, metadata, index namespaces, and recovery checkpoints |
| Storage engine files | ZoneTree | Tree metadata, segments, write-ahead logs, compression, block layout, and merge machinery |

The byte layouts below describe the serialized keys and values passed to ZoneTree. They are not offsets into segment or WAL files. Segment mode and compression can be configured through `StoreOptions`; opening trees through the matching ZoneTree version handles that layer. The current core project references ZoneTree **2.0.1**.
The byte layouts below describe the serialized keys and values passed to ZoneTree. They are not offsets into segment or WAL files. Segment mode and compression can be configured through `StoreOptions`; opening trees through the matching ZoneTree version handles that layer. The current core project references ZoneTree **2.2.0**.

ZoneTree 2.2.0 opens storage format 2.1.10 or newer. See the [storage upgrade instructions](../docs-site/content/docs/reference/configuration/configuration.mdx#storeoptions) for existing databases.

On dataset creation, the engine persists these settings and requires exact matches on every reopen:

Expand Down Expand Up @@ -403,7 +405,7 @@ Activation metadata records historical coverage. Definitions and aggregates pres

An accepted event first enters the ingestion queue. Raw records, session snapshots, rollups, and index copies are then maintained through different write paths. There is no dataset-wide transaction committing all of them together.

`StoreOptions.WriteAheadLogMode` defaults to `AsyncCompressed`. Persistent tree writes follow the configured ZoneTree WAL mode; in that mode a process that dies can lose its most recent writes. A successful tracking call reports queue acceptance, and a crash can lose queued events and buffered aggregates. `Flush` drains prior accepted ingestion work and writes buffered aggregates and session state; it does not make every configured WAL mode synchronous. Clean disposal drains work, flushes, closes stores, and releases the directory lock. `Compact` additionally moves open trees toward merged disk storage.
`StoreOptions.WriteAheadLogMode` defaults to `AsyncPrivate`. A process crash can lose recent writes still queued for the WAL writer. A successful tracking call reports queue acceptance, and a crash can lose queued events and buffered aggregates. `Flush` drains prior accepted ingestion work and writes buffered aggregates and session state. Clean disposal drains work, flushes, closes stores, and releases the directory lock. `Compact` additionally moves open trees toward merged disk storage.

Ingestion workers do not write rollup rows themselves. On flush, a worker hands its buffered rows to dedicated rollup writers (`Ingestion.RollupWriterCount`), each of which owns a share of the rows by key. A writer merges the rows of all workers that flushed since its last write, writes each row once, and only then lets those workers persist their session states. Rollup writes serialize the updates of each row. A row's key selects one of 64 lock stripes of its partition, so writers update different rows of a partition in parallel and the same row one at a time; its covering index copies are written under the same lock, in order. The writer merges a delta with the existing value once, retains the absolute replacement for retries, and finishes a pending replacement before applying a newer delta in its stripe. This prevents retrying a failed upsert from applying the same contribution twice within that write path. It does not provide crash-atomic coordination between raw events and every aggregate tier.

Expand Down
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
matching ZoneTree.Analytics. Pass VersionSuffix (for example preview.1) to pack a pre-release.
-->
<PropertyGroup>
<VersionPrefix>1.0.2</VersionPrefix>
<VersionPrefix>1.0.3</VersionPrefix>
<IsPackable>false</IsPackable>
<Authors>Ahmed Yasin Koculu</Authors>
<Company>ZoneTree</Company>
Expand Down
37 changes: 19 additions & 18 deletions src/ZoneTree.Analytics.AspNetCore/LoggerAdapter.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Microsoft.Extensions.Logging;
using HostLogLevel = Microsoft.Extensions.Logging.LogLevel;
using ZoneTreeLogLevel = ZoneTree.Logger.LogLevel;
using ZoneTree.Logging;

namespace ZoneTree.Analytics.AspNetCore;

Expand All @@ -22,7 +21,7 @@ public static AnalyticsOptions UseLogger(this AnalyticsOptions options, ILogger
/// <summary>
/// Routes engine and storage logs to Microsoft.Extensions.Logging.
/// </summary>
sealed class LoggerAdapter : ZoneTree.Logger.ILogger
sealed class LoggerAdapter : IZoneTreeLogger
{
readonly ILogger logger;

Expand All @@ -35,24 +34,26 @@ public LoggerAdapter(ILogger logger)
/// The minimum level ZoneTree formats messages for. Filtering is left to the
/// Microsoft.Extensions.Logging configuration.
/// </summary>
public ZoneTreeLogLevel LogLevel { get; set; } = ZoneTreeLogLevel.Trace;
public ZoneTreeLogLevel Level { get; set; } = ZoneTreeLogLevel.Trace;

public void LogError(Exception log) =>
Log(ZoneTreeLogLevel.Error, HostLogLevel.Error, log?.Message, log);
public bool IsEnabled(ZoneTreeLogLevel level) => IsEnabled(level, HostLevel(level));

public void LogWarning(object log) =>
Log(ZoneTreeLogLevel.Warning, HostLogLevel.Warning, log, null);
bool IsEnabled(ZoneTreeLogLevel level, LogLevel target) =>
target != LogLevel.None && level >= Level && logger.IsEnabled(target);

public void LogInfo(object log) =>
Log(ZoneTreeLogLevel.Info, HostLogLevel.Information, log, null);

public void LogTrace(object log) =>
Log(ZoneTreeLogLevel.Trace, HostLogLevel.Trace, log, null);

void Log(ZoneTreeLogLevel level, HostLogLevel target, object message, Exception exception)
public void Log(ZoneTreeLogLevel level, string message, Exception exception = null)
{
if (LogLevel > level || !logger.IsEnabled(target))
return;
logger.Log(target, default, message, exception, static (state, _) => state?.ToString() ?? "");
var target = HostLevel(level);
if (IsEnabled(level, target))
logger.Log(target, default, message, exception, static (state, _) => state ?? "");
}

static LogLevel HostLevel(ZoneTreeLogLevel level) => level switch
{
ZoneTreeLogLevel.Trace => LogLevel.Trace,
ZoneTreeLogLevel.Info => LogLevel.Information,
ZoneTreeLogLevel.Warning => LogLevel.Warning,
ZoneTreeLogLevel.Error => LogLevel.Error,
_ => LogLevel.None
};
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net10.0;net9.0;net8.0</TargetFrameworks>
<TargetFrameworks>net11.0;net10.0;net9.0;net8.0</TargetFrameworks>
<LangVersion>13</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>disable</Nullable>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>disable</Nullable>
<ServerGarbageCollection>true</ServerGarbageCollection>
Expand Down
4 changes: 2 additions & 2 deletions src/ZoneTree.Analytics.UnitTests/AdvancedStorageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ public void AccessUsesTheActualTreesAndConfiguredMaintainers()
Assert.That(sessions.Next(), Is.True);
Assert.That(sessions.CurrentValue.PageViews, Is.EqualTo(1));
Assert.That(sessions.CurrentValue.Clone().Dimensions, Is.Not.SameAs(sessions.CurrentValue.Dimensions));
lease.Maintainer.ThresholdForMergeOperationStart = 3;
Assert.That(internalLease.Maintainer.ThresholdForMergeOperationStart, Is.EqualTo(3));
lease.Maintainer.MergeThreshold = 3;
Assert.That(internalLease.Maintainer.MergeThreshold, Is.EqualTo(3));
}

[Test]
Expand Down
15 changes: 9 additions & 6 deletions src/ZoneTree.Analytics.UnitTests/AspNetCoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ZoneTree.Analytics.AspNetCore;
using ZoneTree.Logging;

namespace ZoneTree.Analytics.UnitTests;

Expand Down Expand Up @@ -159,13 +160,15 @@ public void MiddlewarePropagatesApplicationFailures()
Assert.That(Engine.GetStatistics().Errors, Is.Zero);
}

sealed class ThrowingLogger : ZoneTree.Logger.ILogger
sealed class ThrowingLogger : IZoneTreeLogger
{
public ZoneTree.Logger.LogLevel LogLevel { get; set; } = ZoneTree.Logger.LogLevel.Warning;
public void LogError(Exception log) => throw new InvalidOperationException("logger failure");
public void LogWarning(object log) { }
public void LogInfo(object log) { }
public void LogTrace(object log) { }
public ZoneTreeLogLevel Level { get; set; } = ZoneTreeLogLevel.Warning;
public bool IsEnabled(ZoneTreeLogLevel level) => level != ZoneTreeLogLevel.None && level >= Level;
public void Log(ZoneTreeLogLevel level, string message, Exception exception = null)
{
if (level == ZoneTreeLogLevel.Error)
throw new InvalidOperationException("logger failure");
}
}

[Test]
Expand Down
8 changes: 4 additions & 4 deletions src/ZoneTree.Analytics.UnitTests/ConfigurationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public void StoreOptionsAreValidatedWhenTheEngineStarts()
var zoneTreeRule = Assert.Catch(() =>
TestEngine.Create(directory, o => o.Storage.Rollups.DiskSegmentMaxItemCount = 1_000).Dispose());
Assert.Catch(() => TestEngine.Create(directory, o =>
o.Storage.RawEvents.ConfigureWriteAheadLog = wal => wal.AsyncCompressedModeOptions = null).Dispose());
o.Storage.RawEvents.ConfigureWriteAheadLog = wal => wal.EmptyQueuePollInterval = TimeSpan.FromMilliseconds(-1)).Dispose());
Assert.Multiple(() =>
{
Assert.That(engineRule.Message, Does.Contain("Storage.Rollups.MutableSegmentMaxItemCount"));
Expand All @@ -147,15 +147,15 @@ public void StoreOptionsReachZoneTree()
var walModes = new System.Collections.Concurrent.ConcurrentBag<ZoneTree.Options.WriteAheadLogMode>();
using var engine = TestEngine.Create(directory, o =>
{
o.Storage.RawEvents.WriteAheadLogMode = ZoneTree.Options.WriteAheadLogMode.Sync;
o.Storage.RawEvents.ConfigureWriteAheadLog = wal => walModes.Add(wal.WriteAheadLogMode);
o.Storage.RawEvents.WriteAheadLogMode = ZoneTree.Options.WriteAheadLogMode.Private;
o.Storage.RawEvents.ConfigureWriteAheadLog = wal => walModes.Add(wal.Mode);
// Below ZoneTree's recommended minimum: only accepted with AllowUnsafeOptionValues.
o.Storage.Rollups.DiskSegmentMaxItemCount = 1_000;
o.Storage.Rollups.AllowUnsafeOptionValues = true;
});
engine.Track(Event("purchase", "pro", 0));
engine.Flush();
Assert.That(walModes, Has.Some.EqualTo(ZoneTree.Options.WriteAheadLogMode.Sync));
Assert.That(walModes, Has.Some.EqualTo(ZoneTree.Options.WriteAheadLogMode.Private));
}

[Test]
Expand Down
2 changes: 1 addition & 1 deletion src/ZoneTree.Analytics.UnitTests/DimensionIndexTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ public void NonDurableIndexesAreRebuiltEvenAfterOrderlyShutdown()
void Options(AnalyticsOptions options)
{
Configure(options);
options.Storage.DimensionIndexes.Store.ConfigureWriteAheadLog = wal => wal.WriteAheadLogMode = ZoneTree.Options.WriteAheadLogMode.None;
options.Storage.DimensionIndexes.Store.ConfigureWriteAheadLog = wal => wal.Mode = ZoneTree.Options.WriteAheadLogMode.None;
}
using (var engine = TestEngine.Create(directory, Options))
{
Expand Down
4 changes: 2 additions & 2 deletions src/ZoneTree.Analytics.UnitTests/EngineTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -811,9 +811,9 @@ public void RawEventsNeverContainIpOrUserAgent()
new StoreFactory(
options.Storage,
Path.GetFullPath(directory),
new ZoneTree.Logger.ConsoleLogger(),
new ZoneTree.Logging.ConsoleLogger(),
new RetentionClock(options.Retention, new ReportingCalendar(options.TimeZone, options.FirstDayOfWeek))),
new ZoneTree.Logger.ConsoleLogger()))
new ZoneTree.Logging.ConsoleLogger()))
{
raw.Scan("default", Day0.Ticks, Day0.AddDays(1).Ticks, 1, () => events, (list, ticks, value) =>
{
Expand Down
Loading