Skip to content

Cratis Chronicle schema representation for events and read models

Cratis Chronicle uses JSON schemas to describe stored events and read models and to materialize their values when reading them. In the .NET client, use JsonSchemaType when a custom JSON converter writes a different shape from the type’s .NET structure. The attribute makes the schema describe that JSON representation; it does not change serialization.

Primitives map directly. A ConceptAs<T> type, which wraps a primitive in a domain-specific type, normally maps to its underlying primitive. For another converter-backed type, declare the representation explicitly:

using System.Text.Json;
using System.Text.Json.Serialization;
using Cratis.Chronicle.Schemas;
[JsonSchemaType(typeof(string))]
[JsonConverter(typeof(PostalCodeJsonConverter))]
public class PostalCode(string value)
{
public string Value { get; } = value;
}
public class PostalCodeJsonConverter : JsonConverter<PostalCode>
{
public override PostalCode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
new(reader.GetString()!);
public override void Write(Utf8JsonWriter writer, PostalCode value, JsonSerializerOptions options) =>
writer.WriteStringValue(value.Value);
}

View C# snippet source on GitHub

The example’s PostalCodeJsonConverter writes a string rather than an object with a Value property. [JsonSchemaType(typeof(string))] makes the schema describe that string too, so the kernel can read it back using the right representation.

The override preserves the original type’s compliance metadata and nullability. A type marked [PII] for personally identifiable information keeps the metadata used for per-subject encryption, and a nullable use remains nullable in the schema. An explicit JsonSchemaType takes precedence over inferred mappings, including ConceptAs<T> handling. This attribute is a .NET client API.

Chronicle can omit nullable nulls from stored content. For a nullable property, explicit null and an absent property are equivalent: both read back as null. A supplied non-null value is retained, even when it is the underlying type’s default, such as decimal? holding 0 or int? holding 0. Missing non-nullable values materialize as their type defaults where the schema permits them; leaving a property out does not make it nullable.

When verifying stored content, use Chronicle’s schema-aware ContentComparison / VerifyContent path rather than raw JSON equality. It accounts for schema defaults and storage representation. The presence or absence of a property in raw JSON does not establish a separate event fact.

The .NET schema generator includes a defaulted concept property’s underlying type, format, and protection metadata alongside its default. Older generators could emit only {"default":null} for an optional concept constructor parameter. That default-only schema does not discard supplied values: the kernel preserves them even though the property has no declared type.

A default-only property can gain its generated representation within the same event generation, provided its default does not change. The refinement can add type, format, array items, enum members, string patterns and lengths, nested object properties, and compliance or security metadata. During a rolling upgrade, a legacy client can still submit the default-only shape; registration retains the more precise stored schema and its protection metadata. Changing the default or making an incompatible change to an already-typed property requires a new generation.

The .NET client sends the precise event schema when the kernel advertises precise-event-type-schemas during connection. With an older kernel, it registers the legacy shape instead. Event-sequence sink definitions make the same capability check; ordinary read-model schemas always use the precise shape. Registrations that supply only Schema, without a Generations list, must also be compatible with the stored generation and cannot overwrite an incompatible schema.

If you provide a custom IJsonSchemaGenerator, implement GenerateLegacyEventType as well as Generate. The client calls the legacy method when the kernel lacks the capability or the connection does not implement IKernelCapabilities, as can happen with testing or wrapped connections. The default implementation throws LegacyEventTypeSchemasNotSupported rather than reusing the precise schema.

Adding protection metadata affects future appends, not historical plaintext; see Adding PII to an existing event type.

Use a decimal-formatted event property for amounts and other values that need decimal precision. Chronicle carries these values as decimals through event storage, projections, and read-model sinks, without converting them to binary floating point. A concept wrapping a decimal uses the same representation. The storage provider still determines the range and scale a read-model column can hold.

Provider Event content Decimal read-model property
MongoDB Decimal128 Decimal128
PostgreSQL JSON decimal literal NUMERIC
SQL Server JSON decimal literal DECIMAL(38,18)
SQLite JSON decimal literal Invariant decimal text in TEXT, plus a generated numeric sort key
In-memory CLR decimal CLR decimal

The JSON payload on the wire remains a number, not an extended JSON object or a floating-point approximation. Ordinary double and float properties keep their existing floating-point behavior. An untyped BSON Decimal128 containing a fraction is read as a decimal, never truncated to an integer.

When a decimal-formatted property was stored as a double by an older kernel, Chronicle reads the double through its shortest round-trip text. For example, the stored double whose text is 193.58 becomes the decimal 193.58. This avoids introducing extra binary rounding digits on read. It cannot recover significant digits that an earlier writer already lost.

Replay a read model to rebuild it from the event history. MongoDB read-model values written as doubles are replaced with Decimal128 when the replay writes the decimal-formatted values.

A SQL Server DECIMAL(38,18) scalar column supports at most 20 integer digits and 18 fractional digits. Chronicle rounds scalar read-model values to 18 fractional digits, with midpoints rounded away from zero, matching SQL Server’s rounding. Computed values such as 1m / 3m therefore project successfully. Values outside the column’s 20-integer-digit range are refused. Event content retains its original decimal precision.

Existing DECIMAL(18,2) columns round values further to their own scale until replay replaces the table. SQL Server also returns decimals at the column’s fixed scale. Chronicle removes redundant trailing zeros on read: 193.580 reads back as 193.58. The values are numerically equal, but their decimal.GetBits results can differ because the input scale is not preserved.

The SQL migrator adds missing columns; it does not alter existing column types. Replay existing SQL read models before relying on exact decimal writes. Replay creates a fresh table with the new mapping and replaces the old table when the replay succeeds. This is required for SQLite’s former REAL columns and SQL Server’s former DECIMAL(18,2) columns.

SQLite needs a numeric ordering key because its decimal read-model values are stored as text. Chronicle supplies that key in an internal shadow column, outside the projected properties and the Entity Framework (EF) model. Shadow columns are nullable without a default and do not become properties on the read model. The decimal ordering shadow is:

Name pattern Provider Storage Index
__order_{column} SQLite, scalar decimal properties including decimal keys Generated VIRTUAL TEXT When the decimal property declares an index, single (either direction) or as part of a composite index

If a schema property collides with a shadow name (case-insensitively), the schema property wins: the shadow is skipped and the kernel logs a warning. Registration still succeeds, but an operation requiring that shadow refuses explicitly rather than using the schema property’s value.

The kernel adds missing shadows to existing tables without rewriting data. It manages their chronicle_shx_ indexes separately from declared chronicle_idx_ indexes, so declared-index reconciliation and table-renaming logic leave shadow indexes alone. If an old kernel promotes a replay table without shadows, ordinary EF reads and writes remain unaffected. A shadow-specific operation repairs missing columns and indexes and retries once. SQLite catalog probes include generated columns, so a restart does not attempt to add them again.

SQLite’s original TEXT decimal columns preserve digits but still sort as strings in ad-hoc SQL ("10" precedes "9"). Existing REAL-affinity tables still require replay for exact values; non-text legacy values have NULL ordering keys. No floating-point conversion recovers lost precision.

The decimal ordering key is a fixed-width ASCII encoding under SQLite’s default BINARY collation. Numerically equal scales and all signed or scaled zeros have equal keys. NULL remains NULL and sorts first ascending. Sink paging orders decimal keys by this encoding with the original key text as a stable tie-breaker; scalar decimal candidate lookups compare the canonical key, admitting equal scales without materializing unrelated parents. Ad-hoc numeric ranges must compare encoded keys, not ordinary decimal strings. Arbitrary EF decimal expressions over the original property do not use this encoding automatically.

Before replaying a decimal read model, check the source events: replay cannot recover precision already lost from the original event content. Projection registration lifecycle explains when definition changes trigger replay and where to follow the rebuild.