Skip to main content

Calculations

Calculations are the most direct use of Vox's dependency and change tracking. They do more than compute a value: Vox records what each run read, knows when that result may have become stale, and reruns only the affected source entities.

For the team workflow, see Calculate a result once.

A calculation is an IVoxCalculation<TEntity> that writes the properties marked [VoxCalculated] with its type, or with a marker interface or base class that it implements. The calculated fields can be anywhere in the entity, next to owned and imported ones, and actions, imports and other calculations can't write them. The calculation receives the entity, whose reads are tracked, and an untracked copy of it to set the calculated fields on. Changing any other field of the copy fails the calculation, and Vox stores the calculated fields when a value changed. See Owned and mirrored data.

A calculation can also reach beyond its own entity: it can create entities, and calculate fields of the entities related to it, eg an order's calculation that distributes a discount to the order's lines. See Create entities and calculate related entities.

For a draft-enabled owned entity, calculations also run in drafts and releases, but only where their results can differ: for the entities changed there, and for the entities that read something changed there. Everything else reads the published results. Preview pages therefore see calculated values derived from the draft, while the live entity remains unchanged. Dependencies and delayed recalculations keep the draft or release, while what the calculation reads differs there. Once it no longer does, eg after the draft it read is published, its result there is the published one again, and the draft keeps neither the result nor the dependencies. An entity that a calculation creates is previewed the same way: a draft or release reads the entity that its calculations would create, though published content doesn't, and published content creates it once the change is published.

Calculations and cached references also run at the contexts of the variations they read. If a product caches the names of its categories and a category has a Swedish variation, the product is calculated again in Swedish. The result is kept only where it differs from the product's own result, and a Swedish read applies it like a variation of the product. Other languages, and the product's own stored values, keep the result calculated without contexts. When the variation is deleted, the result calculated for it is removed. An entity type without drafts reads published content in a draft or release, so a draft variation of something it reads changes nothing for it.

The values of a VoxVarying property aren't variations: every read has the values of every context, whatever it selects. So a calculation that reads a setting that varies by market, eg the show-price flag of each market, runs once, and splits the values by market itself; it isn't calculated again in each market. A variation of another property of the setting at Market=se still makes it run in Sweden too. An explicit recalculation, eg IVoxRecalculator.RecalculateAllAsync or a migration's Recalculate, follows the same rule: it evaluates published content, the addresses where the calculation already ran, and the drafts, releases and keys where the entity has content of its own other than values of varying properties. A membership of a market isn't such content, so it doesn't make the calculation run in that market either; a calculation that must run per market uses [VoxRunsPerContext].

Settled saves​

A save evaluates the saved entity's own calculations and publishes the entity with their results, in the same operation. The saved entity is never visible with calculated values that don't reflect its own inputs, and there's nothing to wait for or poll after a save.

For example, a variant's margin and selling price are calculated from its purchase price. An editor or an integration changes the purchase price from 100 to 120:

  1. The save evaluates the margin and selling price calculations with the new purchase price, and publishes version 2 with purchase price 120, its margin and its new selling price, in one commit with one history entry and one event.
  2. IVoxEntityUpdater.UpdateAsync returns that version 2, and a read straight after it, on any node, returns the same.
  3. The product whose price range reads its variants is another entity. The save records a dependency change, and the processing recalculates the product's price range in the background.

Which calculations a save evaluates follows from what they read: those of the saved entity that read a field the save changed, as their recorded dependencies tell, and all of them for a created entity or a calculation that never ran. A save that changes nothing a calculation reads, eg a variant's description, evaluates nothing. A category whose own calculation counts its 20,000 products doesn't count them when it's renamed; the count follows product changes in the background. A calculation evaluated in a save can read other entities, eg a product's price range reads its variants, and reads them as they're published.

Index-backed links (IVoxRelationReferences<T>) are written after the save's evaluation, so a calculation that reads them sees the links from before the save. When a save changes such links, eg links a product to two more categories, the calculations of the entities at both ends that read them are evaluated again in the background, and a product whose calculation counts its categories catches up a moment after the save.

Everything needed to make the saved entity consistent runs in the save:

  • Calculations per context. When a calculation that runs per context, see Calculated values per context, reads a field the save changed, the save evaluates every run of it: a change of a product's base price evaluates its price calculation once per market it's a member of, eg 30 times for 30 markets. An application that wants one evaluation writes one calculation that iterates over the markets. A save of a value at a context, eg the product's Norwegian base price, evaluates the calculations that read it at that key, eg the Norwegian run, and writes their results with the value. Removing values at a context, changing links at a context, and a value at a key that lacks some of the context types a calculation runs per, eg a Swedish value for a calculation that runs per market and language, are calculated in the background instead.
  • Cached references. A save that changes a reference, eg a product whose brand changes from Acme to Globex, refreshes the cached values from Globex in the save. A change of Globex itself reaches the products that cache it in the background.
  • Memberships. The contexts an entity gives itself, through its own values, its own property relations (with the memberships of the entities they lead to, one level) and its membership calculation, with its explicit memberships overriding, are worked out in the save, with the runs per context they add: a product added to the Norwegian assortment is published as a member of Norway with its Norwegian price. A link saved from the other side, eg the assortment's list of products, or an index-backed link, and the memberships of the entities that inherit from the saved one, follow in the background, and so do the memberships of a save in a draft or release.
  • Groups. A calculation that calculates fields of other entities through declared targets makes its root and those entities a group that's saved together. An order's calculation that splits its discount over its lines runs in the save of a line whose quantity changed, and the order and every line whose share changed are published together. A line's save that changes nothing the order's calculation reads, eg its note, saves the line alone. A group is bounded by VoxOptions.Processing.MaxCalculationOutputs (1,000 outputs per evaluation): more fails the save, with an error that says to calculate from narrower roots. The root reads the saved members' new values through the relation that leads them to it, eg with LoadRelatedAsync, or counts, checks or pages them with CountRelatedAsync, IsRelatedAsync or ForEachRelatedPageAsync; a root that finds its targets with a query fails the save with an error that says so. What a calculation of the saved entity creates is created in the same save.

Editors working on different lines of the same order don't conflict: an update checks the version of the origin of the fields it writes, so when line 2's save gives line 1 a new share, line 1's owned version doesn't move. A write of a whole entity with an expected version, eg an import that sends ExpectedVersion for line 1, can conflict with a group save.

A calculation that fails fails the save​

If a calculation throws during a save, the whole save fails and nothing is written: not the entity, not the other entities of its group, no event. The save throws a VoxCalculationFailedException with the entity, the calculation, the address it failed at, eg the Norwegian run, what it threw, and whether the failure is transient, eg a timeout while it read another entity. The save isn't retried: a bug fails the same way twice, and a transient failure is retried by the caller. The API answers 422 with problem details naming the calculation, or 503 with Retry-After when it's transient; MCP answers calculation_failed, or unavailable marked retryable; the TypeScript client throws a VoxCalculationError. A bug in a calculation therefore blocks every save that has to run it until a fix is deployed.

While a model migration builds the query storage of a field, queries by it would return partial results, so a save whose calculation queries such a field fails with the transient error. Release the index before a calculation that queries it.

In a batch the failure follows the batch's own boundaries: an Atomic batch update fails as a whole, while a PerEntity batch update and an import fail the entity whose calculation failed, with the other entities of its group in the batch, and save the rest.

Batches, imports and transactions​

A batch update and an import evaluate the calculations of the whole batch together, for speed: an import of 500 products whose calculations read the same 10 categories reads those categories once. Each entity is evaluated against the other entities as they're published, not against the new values of other entities in the same batch: a product imported with its variants gets its price range from the published variants, and catches up in the background. Groups are the exception, since they're saved together by definition.

A save inside IVoxTransactionRunner settles its calculations inside the transaction, so they read what it staged: a transaction that saves three variants with new prices and then their product calculates the price range from the new prices. Save the entities a calculation reads before the entity that reads them, and use a declared target when entities must settle together; two entities that read each other without one have no save order that settles both.

Saves and concurrent changes​

A save whose calculations read other entities is protected against a change of what they read that commits meanwhile. Say a product's save reads its 3 variants, and an import commits a new price for variant 2 right after the save read it. The variant's dependency change can't find the product's new dependency on it yet. The save draws a read start before its calculations read another entity, and checks its reads after its commit, so the product is calculated again in the background. A save whose calculations only read the entity itself, eg a margin from a purchase price, pays nothing for this.

A calculation that queries its own entity type sees its own entity as it's being calculated, not as it's still published: a product calculation that counts the products of its category counts the product in its new category. Where only the database could place the entity exactly, eg when its change moves it out of a page of a query with a take, the calculation fails with an error that says so; query every match instead.

Consistency stops at the entity: the product whose price range reads the variant follows when its own calculations are done in the background. Within a run, though, the processing looks ahead across entities. Say a variant's adjustment is twice its product's input, and the product's total is its input plus the variant's adjustment. When the product's input changes from 2 to 3, the processing evaluates the variant against the product's unpublished input (adjustment 6), then the product again against the variant's unpublished adjustment (total 9). It publishes both together in one transaction: nobody ever sees the product's total of 3 + 4, and the return to the product isn't mistaken for a cycle, since it reads another field. Such a group is bounded (VoxOptions.Processing.MaxFlushGroupSize, 200 entities; 0 turns the lookahead off) and stays within one storage provider. GetAllAsync reads the unpublished values of the group's entities of its type, including those that are being created with it, and LoadRelatedAsync from the other end of a relation reads the stored links while the group's entities keep their links, eg a product that reads its variants whose calculated decisions changed. A calculation that would need another entity's unpublished values where Vox can't give them exactly, eg a tracked query over that entity's type, the inverse links of a relation that an entity of the group changes, or a read of it at a market, isn't part of the group: it's evaluated once the others are published. Calculations of two entities that keep changing each other never settle in a group and are stopped as before. A calculation that fails for good in the background keeps the previous version visible, records an assessment, and parks the work behind it until a corrective change or a retry (POST api/calculations/retry, IVoxRecalculator.RetryAsync).

The assessment is Vox's own vox-processing assessment, which every entity type with calculations, calculated memberships, cached references or side effects has, and every authored entity type, for its scheduled publications. It has one result per failure, at the address it failed at, eg calculation-failed for the variant's selling price calculation in Sweden, or publication-failed when a settled change can't be published because another entity already has its unique SKU. Only the failure itself is assessed: the product whose price range waits for that variant has no finding of its own. A result is cleared when what failed succeeds again, not by an unrelated later change of the entity. A side effect that fails is a side-effect-failed finding of the published entity until a delivery succeeds.

Business work that must follow a consistent update, eg activating a price, is an IVoxEntityUpdateSideEffect<TEntity>: Vox records its delivery in the commit of the publication and delivers it at least once.

Calculated values per context​

A calculated field can vary, eg a VoxVarying<Market, decimal?> price with a value for each market. Usually the calculation sets all its values in one run: it reads what it needs once and splits it by market. That's the simplest and cheapest way, eg for a product's prices, which come from its variants' prices per market:

public class ProductMarketPriceCalculation : IVoxCalculation<ProductBase>
{
public async Task CalculateAsync(ProductBase product, ProductBase result, IVoxCalculationContext context,
CancellationToken cancellationToken)
{
var variants = await context.LoadRelatedAsync<ProductVariantBase>(product, cancellationToken);
// The lowest variant price in each market over time, see Values that change over time
result.Pricing.FromPrice = new VoxVarying<Market, VoxTimeline<decimal>>(variants
.SelectMany(variant => variant.Prices)
.GroupBy(price => price.MarketId)
.Select(market => KeyValuePair.Create(market.Key,
VoxTimeline.Combine(market.Select(price => price.Price), prices => prices.OfType<decimal>().Min()))));
}
}

Some inputs can only be read in a context, though: a variation of a setting at Market=se, which a read only sees with Sweden selected, a tracked query or relation read in a market, which only matches the entities that are members of it, or a value resolved through a context's fallbacks. For those, mark the calculation [VoxRunsPerContext]. It then runs once for each context that its entity is a member of, reads in that context, and sets that context's value only:

[VoxRunsPerContext]
public class CategoryMarketStatisticsCalculation : IVoxCalculation<Category>
{
public async Task CalculateAsync(Category category, Category result, IVoxCalculationContext context,
CancellationToken cancellationToken)
{
var market = await context.GetSelectedContextAsync<Market>(cancellationToken);
result.MarketStatistics.SellableProductCount[market.Id] = await context.Query<ProductBase>()
.WhereRelated(product => product.Merchandising.Categories, [category.Id])
.ExistsIn<Market>(market.Id)
.CountAsync(cancellationToken);
}
}
  • Which runs there are. The context types are those of the fields, and the contexts are the entity's memberships, see Contexts. A category in Sweden and Norway gets two runs, and creating Denmark gives it none until it has products there. A calculated varying field never makes the entity a member of anything, so the entity type must be a member of the context types in another way, eg [VoxMemberOf(typeof(Market), Through = ["products"])]. Fallbacks and invariant values add no runs.
  • When they run. Joining a context runs the calculation there, leaving it removes that context's value, and a change of what a run read runs only that run, eg renaming Norway runs the Norwegian runs.
  • What a run may change. Only its own context's value of the calculation's fields: changing another context's value, or another field, fails the run without writing anything. Removing its own value means it has none.
  • Its fields. All of them must vary on the same context types, in the same order, and none may contain references. A calculation can't calculate an ordinary field per context, since every run would overwrite it.
  • Drafts. A draft that differs keeps the complete values of every context of the field, and its runs keep them current when published inputs change.
  • GetSelectedContextAsync<TContext>() gives the run its context, read like any other entity, so that changing it, eg the market's settings, runs it again. It also works in a projection published in a context.

Running per context costs a run per context and entity, so use it only for inputs like these. Changing a calculation to run per context, or back, removes its stored values and calculates them again.

When the context comes from the rows a calculation reads, eg a price list per customer group, and the field shouldn't declare it, the calculation can set its values at keys it chooses instead, see Results at chosen keys.

public class ProductAvailability
{
public virtual List<MarketPrice> Prices { get; set; } = [];
public virtual bool IsInStock { get; set; }
}

public class Product : IVoxExternalEntity
{
// Built-in entity properties and other domain properties omitted.
[VoxCalculated(typeof(ProductAvailabilityCalculation))]
public virtual ProductAvailability Availability { get; set; } = new();
}

public class ProductAvailabilityCalculation(TimeProvider timeProvider) : IVoxCalculation<Product>
{
public async Task CalculateAsync(
Product product,
Product result,
IVoxCalculationContext context,
CancellationToken cancellationToken)
{
var prices = await context.LoadRelatedAsync<Price>(product, cancellationToken);
var stock = await context.LoadRelatedAsync<StockLevel>(product, cancellationToken);

foreach (var boundary in prices
.SelectMany(price => new[] { price.ValidFromUtc, price.ValidToUtc })
.OfType<DateTime>())
{
context.ReevaluateAt(boundary);
}

var now = timeProvider.GetUtcNow().UtcDateTime;
result.Availability.Prices = prices
.Where(price =>
(price.ValidFromUtc == null || price.ValidFromUtc <= now) &&
(price.ValidToUtc == null || now < price.ValidToUtc))
.Select(price => new MarketPrice
{
MarketId = price.Market.Id,
Amount = price.Amount,
Currency = price.Currency,
})
.ToList();
result.Availability.IsInStock = stock.Any(level => level.OnHand - level.Reserved > 0);
}
}

Vox tracks the serialized properties that a calculation reads from its source and from entities returned by IVoxCalculationContext. Changing an unrelated property does not rerun the calculation. Entity and nested-object properties are therefore virtual; Vox validates the complete model at startup and reports every getter it cannot proxy. Collections and dictionaries are dependency boundaries, so reading one depends on that complete value.

Read other entities through GetAsync, GetManyAsync, GetAllAsync, LoadRelatedAsync, and GetContextIdsAsync. GetAllAsync depends on entities being added or removed and on the properties actually read from its results. A count-only read is not triggered by an update to an existing entity.

GetAllAsync and LoadRelatedAsync read whole collections, which is meant for small sets, eg languages, markets or the images of a product. They fail when a set is larger than a complete read gets, see the budgets in Querying and search, rather than materializing a catalogue. Large sets are reduced in the storage or a page at a time instead:

// The number of products in a category, counted in the storage. A relation to several types, eg every kind of
// product, is counted as a type that all of them are, since the storage doesn't tell its links apart by type
var count = await context.CountRelatedAsync<Product>(category);

// Whether a product is in a category
var isRelated = await context.IsRelatedAsync<Category>(product, "jackets");

// A sum over the millions of products of a brand, one page in memory at a time
var stock = 0;
await context.ForEachRelatedPageAsync<Product>(brand, 500, (page, _) =>
{
stock += page.Sum(product => product.Erp.Stock);
return Task.CompletedTask;
});

// A sum over the products that match a tracked query
await context.Query<Product>().Where(product => product.Status == ProductStatus.Active)
.ForEachPageAsync(500, (page, _) => { stock += page.Sum(product => product.Erp.Stock); return Task.CompletedTask; });

Each records its dependency, also when nothing matches, so adding or removing a link, or a change of what a query matches, also behind a page that was processed, calculates the calculation again. Each entity of a page is read as GetManyAsync reads it. An evaluation that's cancelled, or fails while it processes a page, completes nothing. An evaluation that records more dependencies than VoxReadBudgets.DependencyWarningThreshold, and every complete read of an entity type, are reported by the meter CommerceMind.Vox.Reads. Vox records IDs even when they do not exist, empty relations, and empty membership reads. Creating missing data therefore still triggers a recalculation. Relation loads also depend on the links, so adding, removing, or retargeting a link triggers the owner.

LoadRelatedAsync works the same for both kinds of many-reference relations: an embedded List<VoxReference<T>> and an index-backed IVoxRelationReferences<T> (see Embedded and index-backed collections). It's the way to read an index-backed relation in a calculation, from either side, since that relation isn't in the owner's JSON. Eg a variant availability calculation finds the campaigns of a product this way, so that only linking or unlinking that product recalculates its variants:

var product = await context.GetAsync<ProductBase>(variant.Product.Id, cancellationToken);
var campaigns = await context.LoadRelatedAsync<Campaign>(product!, nameof(Campaign.Products), cancellationToken);

To read a relation of many entities, eg the prices of every product of a bundle, pass them all to LoadRelatedAsync<Price>(products, cancellationToken), which reads their links together and returns the related entities of each, recording the same dependencies as one call per entity. context.PreloadAsync(products, preload => preload.Include(product => product.Variants)) prepares relations that the calculation or its helpers read later, eg through product.Variants.LoadAsync(): it reads them in batches into the evaluation's read cache scope, and only what the calculation then reads becomes a dependency.

Automatic tracking can be suppressed for a block, and explicit dependencies can be declared inside or outside that block:

using (context.Dependencies.SuppressAutomaticTracking())
{
var settings = await context.GetAsync<CommerceSettings>(cancellationToken);
BuildTemporaryLookup(settings);

context.Dependencies.DependOn(settings, value => value.TaxConfiguration);
}

context.Dependencies.DependOn(product, value => value.Commerce.Price);

Explicit APIs also cover whole entities, entity sets, entity-set membership, relations, and context memberships. Suppression flows across await, can be nested, and only affects automatic tracking; explicit dependencies are always kept.

External state can participate in the same dependency graph. Declare an application-defined name and value pair while calculating or projecting, then publish that exact pair when the external value changes:

context.Dependencies.DependOnCustom("exchange-rate", "EUR/SEK");

// In the importer, webhook, polling job, or other integration that detects the change:
await dependencyChanges.PublishChangeAsync("exchange-rate", "EUR/SEK", cancellationToken);

Inject IVoxDependencyChangePublisher into the integration that detects changes. Publishing is durable: matching calculated properties, context memberships, cached references, and entity projection publications become pending work of the processing in the same commit. Names and values are application-defined; use a stable value to invalidate a shared resource, or an external object ID to target only consumers of that object. The batch step of a projection, which loads external data for many entities at once, declares such a pair for one entity of its batch with context.For(entity).Dependencies, see batch loading.

The balances of tracked Accumulators, eg the stock on hand of a position, are read through the context, which records a dependency on each balance, so a committed change of it evaluates the calculation again:

var balances = await context.GetBalancesAsync(StockPosition.OnHand, positionIds, cancellationToken);
result.InStock = balances.Any(balance => balance.Value - balance.HeldOut > 0);

Derive a coarse value where you can, eg in stock or not: an unchanged result isn't published, while a copy of the exact quantity publishes the entity on every checkout. Reading an Accumulator that isn't declared tracked: true fails.

A coarse value is cheaper still with a threshold read, which turns the available amount into the value with an expression, and evaluates the calculation again only when a change takes the amount across one of its thresholds, eg from 1 to 0 but never from 100 to 99:

result.InStock = (await context.GetBalancesAsync(StockPosition.OnHand, positionIds, stock => stock > 0, cancellationToken))
.Any(inStock => inStock);

Put results that change often in a top-level property of their own, eg Availability with only calculated fields, rather than next to owned fields in one object. Entity Framework storage then writes only the calculated values when they change, not the rest of a large entity, see Calculated values in a column of their own.

For a singleton entity such as shared calculation settings, use the parameterless GetAsync<T> or TryGetAsync<T>:

var settings = await context.GetAsync<CommerceSettings>(cancellationToken);

It registers the same entity dependency without exposing a synthetic ID. TryGetAsync records a missing singleton too, so creating the settings later triggers the calculation. See Singleton entities.

Dependencies are replaced after each successful run. A calculation that no longer reads an entity stops depending on it. Recalculation is durable; chains settle naturally because unchanged calculated values aren't published again.

Calculated values in a column of their own​

Entity Framework storage keeps each published entity as a JSON document in a row of its entity type's table. For a type with calculated fields, the row keeps the calculated properties in a second column, and everything else in another. When a recalculation changes a product's availability, the database receives the small calculated column, not the product's descriptions and imported data again, and the processing publishes the new results without reading the product again. For large entities that are recalculated often, this cuts the database's write volume by about half when the calculated values are half of the entity, and by more than 80% when they're a tenth of it. Reads combine the two columns in the same query, at a small cost.

  • What goes in the calculated column. A top-level property goes there only if every field in it is calculated, eg Pricing or Rating. An object that mixes owned and calculated fields is stored with the owned data as a whole, so a change of its calculated field writes the whole entity. Give results that change often a top-level property of their own.
  • Cached references. A refresh of a cached reference inside an owned or imported field changes that field, so it writes the whole entity. A type whose recalculations usually refresh such a reference gets little from the split.
  • History. History and the previous version still store a whole copy of the entity for every changed result, so for those types the split saves about half as much.

Redis storage keeps one document per entity.

Calculated references​

A calculated field can hold references to entities: a VoxReference<T>, a list of them, or an object that contains them. Like every reference property, it declares a relation, and that relation is a full relation: its links are in the relation index, so the inverse relation, LoadRelatedAsync from the other end, tracked queries by the relation, memberships declared through it, and relation change events all see them, like the links of an owned reference.

The typical case is the image that lists a product. Media is often on the variants, eg an image per color, so which image represents the product depends on the product, its variants and their availability:

[VoxTitle($"{nameof(Content)}.{nameof(ProductContent.Name)}")]
public abstract class ProductBase : IVoxAuthoredEntity, IVoxEntityLayout<ProductBase>
{
// Lists picture a product by its calculated image
public static void ConfigureLayout(VoxEntityLayoutBuilder<ProductBase> layout) =>
layout.Image(product => product.ListingImage);

// Built-in entity properties and other domain properties omitted.
[VoxCalculated(typeof(ProductListingImageCalculation))]
[VoxRelation(InverseName = "listedProducts")]
public virtual VoxReference<Image>? ListingImage { get; set; }
}

public class ProductListingImageCalculation : IVoxCalculation<ProductBase>
{
public async Task CalculateAsync(ProductBase product, ProductBase result,
IVoxCalculationContext context, CancellationToken cancellationToken)
{
var variants = (await context.LoadRelatedAsync<ProductVariantBase>(product, cancellationToken))
.OrderBy(variant => variant.CreatedAtUtc).ToList();
// The product's own media first, then the media of the variants that can be bought, then of any variant
var candidates = product.Content.Media
.Concat(variants.Where(variant => variant.Availability.IsPurchasable).SelectMany(variant => variant.Media))
.Concat(variants.SelectMany(variant => variant.Media))
.Select(reference => reference.Id).ToList();
var images = (await context.GetManyAsync<Image>(candidates.Distinct(), cancellationToken))
.Select(image => image.Id).ToHashSet();
var listing = candidates.FirstOrDefault(images.Contains);
result.ListingImage = listing == null ? null : new VoxReference<Image>(listing);
}
}

The links of a calculated relation follow its calculated value, wherever that value is read from:

  • In published content, they're the links of the published value.
  • In a draft or release, the entity has links of its own there only while it has calculated results of its own there. If a draft takes a variant out of stock and the product calculates a different image there, the draft reads the new image and its link, while published content still reads the old ones. Once the draft's result is the published one again, eg after the variant's draft is reverted or published, the draft's links are removed with its result. When a draft or release is published, its calculated results and their links are discarded, and published content calculates them again. An entity created in the draft or release is the exception: it's published with its calculated values as their first published values, so its listing has an image right away, and the recalculation in published content corrects them if they differ.
  • At contexts, eg in a market where another variant is in stock, the result calculated there is linked there only, and a scope's own results beat those of its ancestors at the same contexts, as calculated values do.

The calculation is the only writer of a calculated relation, so it's read-only from both ends: no action, cell, import or relation change sets it, owned writes of the entity keep its links, and the admin shows it as calculated on the entity and on the related entities. A calculated relation grants nothing on its own, eg a membership through it needs [VoxMemberOf(Through = ...)] like any other, and [VoxMyRelation] on it makes access follow the calculation. Index-backed relations, IVoxRelationReferences<T>, can't be calculated: they aren't part of the entity's value, and a calculation writes values, not link changes.

A change of another entity that the calculation reads reaches the product in the background, so for a moment after a variant changes, the listing still shows the previous image; a save of the product itself settles it in the save. The cached values of a calculated cached reference, see Entities and relations, are filled by Vox after the calculation and kept while the reference is the same.

Explain calculated fields in plain language​

Editors, API clients and agents see a calculated field's value, but not the business rule behind it. A calculation can explain each field it calculates in plain English, and the admin UI shows the explanation in a dialog that an information button next to the field's label opens. describe_entity_type and get_calculation in MCP and the explanation of each field in GET /api/entity-types serve the same text. It describes the rule in the deployed calculation; it isn't a trace of how a particular stored value was calculated. Explanations are for those who may read the entity type, and never contain code, so they don't need vox:ReadSource.

Write an explanation with the code​

Write the explanation of a field on its calculation, by the field's canonical path. Separate paragraphs with a blank line:

[VoxFieldExplanation("pricing.fromPrice",
"For each market, this is the lowest price among the product's variants. A variant's campaign price is used " +
"when it has one; otherwise its regular price is used.\n\nMarkets where none of the variants has a price are left " +
"out, so the product has no from price there.")]
public class ProductMarketPriceCalculation : IVoxCalculation<ProductBase> { /* ... */ }

An explanation written in the code is maintained with it, so it's never shown as outdated, and it wins over a generated one. A path that the calculation doesn't calculate, or a second explanation of the same field, is a build warning, and the explanation isn't attached to another field. A field is one of the entity type's semantic fields, those of GET /api/entity-types: pricing.fromPrice and pricing.priceRange are two fields, while the minimum and maximum of a price range, the markets of a varying value and the rows of a list are parts of one field and share its explanation.

A calculation that calculates fields of another entity type, or creates entities, explains them by the type: OrderLine:discountAllocation for a field of the lines an order's calculation calculates, and create:RenewalContract for when it creates a contract, see Create entities and calculate related entities.

Generate the others​

The fields without one can have an explanation generated by a language model, with vox-explain, a .NET tool that reads the calculation's code and writes reviewable mapping files, one per calculation class, in vox-explanations next to the model project, eg vox-explanations/Shop.ProductMarketPriceCalculation.explanations.json:

{
"formatVersion": 1,
"calculation": "Shop.ProductMarketPriceCalculation",
"fields": {
"pricing.priceRange": {
"text": "For each market, this shows the lowest and the highest price among the product's variants...",
"codeHash": "230f3216..."
}
}
}

Commit the mapping files with the code. Every build reads them and compiles the explanations into the assembly, so the deployed application serves them without the repository, the mapping files or a model. A build never calls a model or changes the mappings.

The model is given the calculation's code with every comment, and the code of its helpers: the types marked [VoxCalculationHelper] that it reaches through the code of the project, and those it selects with [VoxCalculationDocumentation(Helpers = [...])]. Comments carry intent and terms that code alone doesn't, so write them for a business reader. Guide the generation of a calculation with [VoxExplanationGuidance("Explain this for a merchandiser; describe the campaign-price fallback and avoid implementation terms.")]. The search for helpers follows the classes, methods and properties that the code refers to, through unmarked code too, which isn't given to the model, and an interface or abstract class to its implementation when the project has exactly one. It doesn't look into referenced assemblies, eg the framework or packages, or follow what's only resolved at runtime, eg through dependency injection of several implementations. The model infers what such code does from its names. Types of *.vox.json entity contracts are analyzed with the authored partial classes that add calculated fields to them.

Generation sends the selected source to the configured model provider, also of a calculation whose source isn't embedded in the assembly with [VoxCalculationDocumentation(EmbedSource = false)]. Explanations never put the source back into the assembly.

Outdated and unverifiable explanations​

Each generated explanation records the hash of the code it was generated or reviewed against: the calculation's source and its helpers' source, with comments. The build compares it with the current code, and the admin UI shows an explanation of changed code with a notice that it may no longer match how the value is calculated, rather than hiding it. A refactoring or a changed comment counts as a change too; a framework or package update doesn't, since that code isn't part of the hash. When the source of a selected helper isn't in the build, eg it's in a referenced assembly, the explanations can't be checked: they're shown with a notice that Vox couldn't check them, and they aren't regenerated from part of the code. A field without an explanation has no button.

Use vox-explain​

Install the tool as a local tool of the repository, and pick the provider and a model of it that supports native JSON schema output. Both OpenAI and Anthropic are supported:

dotnet new tool-manifest
dotnet tool install CommerceMind.Vox.Explanations.Cli
export VOX_EXPLAIN_API_KEY=...
dotnet vox-explain generate --project src/Shop/Shop.csproj --provider anthropic --model <model>
  • collect builds the project to find its compiler inputs, writes a source request per calculation to vox-explanations/requests, which other tools can use, and reports which explanations are missing, outdated or unverifiable. It needs no model.
  • generate also asks the model for the missing and outdated explanations that aren't written in the code, one request per calculation with all its fields, and writes them to the mapping files with the current code hash. A run whose mappings are complete and current doesn't need a provider or an API key.
  • accept --calculation Shop.ProductMarketPriceCalculation [--field pricing.priceRange] records that the explanations you reviewed still describe the current code, eg after a refactoring, by stamping the current hash on them, without a model.

The provider settings are --provider openai|anthropic, --model, --endpoint for another base URL and --api-key, or VOX_EXPLAIN_PROVIDER, VOX_EXPLAIN_MODEL, VOX_EXPLAIN_ENDPOINT and VOX_EXPLAIN_API_KEY (or OPENAI_API_KEY and ANTHROPIC_API_KEY). --concurrency sets how many calculations are asked at once, and --timeout and --max-output-tokens limit each request.

Review the changed mapping files like code, edit a text by hand if you like, and commit them yourself; the tool never stages or commits. An edited text keeps the hash it was generated against, so it stays current until the code changes; running generate again replaces only explanations that are missing or outdated. An answer that isn't complete, has a field that wasn't asked for, was cut short or refused, or a model that doesn't support the schema, leaves the mapping as it was with a warning, and isn't asked again another way. Mappings of renamed or removed calculation classes are left as unused files to delete when you like.

Generate in release builds​

A release build in CI can generate before it compiles, so the explanations it deploys are current:

dotnet build -c Release -p:VoxGenerateExplanations=true \
"-p:VoxExplanationArguments=--provider openai --model <model>"

The build writes its compiler inputs, runs dotnet vox-explain generate on them and compiles the mappings it wrote into the same build. Ordinary local, IDE and design-time builds never generate. VoxExplanationCommand sets another command for the tool. Any problem with the explanations, a provider that can't be reached included, is a warning, VOX006 to VOX010 or VOX021, also with warnings as errors, and the build compiles the explanations it has with their actual freshness.

VoxExplanationsRoot sets where the mappings are, by default vox-explanations next to the project. A CI that builds several brands, environments or branches whose code may differ gives each its own root, eg -p:VoxExplanationsRoot=$(ExplanationStore)/acme/production/main/Shop, and runs one build at a time per root. A lock per calculation keeps two runs from writing the same mapping at once, and a mapping is replaced whole, so a build that reads it sees the old or the new file.

Explain calculated results with assessments​

A calculated value answers what the current result is. The same run can also explain why by emitting an assessment through context.Assessments:

var assessment = context.Assessments.For<ProductAvailabilityDefinition>();
assessment.Metric(definition => definition.AvailableQuantity).Set(result.Availability.AvailableQuantity);
if (result.Availability.AvailableQuantity == 0)
{
assessment.Finding(definition => definition.NoInventory)
.Add("No inventory is available.", "inventoryLevels");
}
assessment.SetOutcome(result.Availability.IsPurchasable
? VoxAssessmentOutcome.Pass
: VoxAssessmentOutcome.Fail);

The definition declares the stable assessment, finding, and metric names once; the lambda selects those typed handles. Vox stores produced assessments only after a successful calculation. If the calculation throws, its previous successful result is retained and marked Error. Omitting a previously produced assessment on a successful run removes that producer's result. See Entity assessments.

Reading inside a calculation​

Every evaluation reads through an IVoxEvaluationContext, from the namespace CommerceMind.Vox.Abstractions.Evaluations: calculations, membership calculations, assessments and entity projections. It has the tracked reads (GetAsync, LoadRelatedAsync, Query<TEntity>(), GetBalanceAsync and the rest), Dependencies, Assessments, EvaluatedAtUtc and ReevaluateAt. A calculation's IVoxCalculationContext adds what only a calculation produces: Create, ResultFor and AtKey. A helper that only reads, eg one that builds an image URL or walks a category path, takes an IVoxEvaluationContext, so a calculation and a projection can both call it.

While Vox evaluates a calculation, an entity projection or an assessment, reads through an IVoxEntityStore are redirected through the evaluation context, so they read the same draft or release and contexts as the evaluation, and what they read becomes a dependency. Queries and searches through a store throw, since their results can't be tracked, and so do writes through the entity updater. Query through the context instead, see Tracked queries. Wrap a deliberate untracked query in VoxEvaluationScope.AllowUntrackedReads(); its results don't recalculate anything when they change. Reads that a store can't see, eg calls through an HttpClient, aren't tracked either. When a calculation reads the campaigns, collections or offers whose rule selects its entity, declare a reach instead, see Policy entities that select what they apply to.

Tracked queries​

context.Query<TEntity>() runs a filtered query whose consumer is calculated again whenever a committed change can alter what it returned, without depending on each entity it matched:

product.ActiveProductsOfBrand = await context.Query<Product>()
.Where(item => item.Brand == product.Brand && item.Status == ProductStatus.Active)
.CountAsync(cancellationToken);

var cheapestVariants = await context.Query<Variant>()
.Where(item => item.Family == product.Family)
.OrderBy(item => item.Price)
.Take(10)
.ToListAsync(cancellationToken);

It supports Where with comparisons, &&, ||, !, null checks and Contains over filterable fields, sorts by sortable fields, Skip and Take, WhereRelated (with descendants by a tree relation), ExistsIn<TContext>, and Include/ThenInclude, which prepares relations of the returned entities without making them dependencies until they're read. ToListAsync, FirstOrDefaultAsync, CountAsync and ToResultAsync with its total count are its materializers. Assessment, cell, scope and draft status filters, facets, search text, explicit scopes and contexts are rejected before anything is read: a tracked query reads in the evaluation's selection.

A tracked query reads the published values of query fields and published links and memberships, like any query at a key, also in a draft or release: a draft calculation that counts active products doesn't see the draft's own status changes. Its query dependencies never make results differ in a draft or release.

Saves only capture the values of the fields, relations and entity types that tracked queries use, which Vox's source generator finds in the lambdas passed to the builder, wherever it's passed. A lambda it can't read, eg one stored in a variable, is reported with the warning VOX003; declare its fields with [VoxTrackedQueryField] on the property, or on the assembly with the entity type and the path of its CLR properties, and relations with [VoxTrackedQueryRelation]. A query by a field, relation or entity type that isn't tracked is rejected before it reads anything.

A release that starts tracking a field, eg a new calculation that counts products by brand when no tracked query read brand before, is deployed with downtime. The previous release's saves don't capture the new field, so while both releases write, a product saved through the previous release doesn't reach the new query, and its count stays stale until another change reaches it. After a rolling deployment of such a release, recalculate the calculation's entity type, eg with a migration's Recalculate. See deployments.

Policy entities that select what they apply to​

Many calculations on a large entity type depend on a few entities that hold business rules, eg the campaigns that discount products, the rule-based collections a product is in, or the offers that apply to a SKU. Each of these policy entities selects the entities it applies to with a selector, eg "brand is Hario and category is brewing". A tracked query that reads every campaign would make every product depend on every campaign's rule, so changing one campaign would calculate every product again. A reach lets the campaign's change calculate exactly the products its old and new rule select.

Declare the reach on the calculation, with the selector property of the policy type:

[VoxReachedBy(typeof(Campaign), nameof(Campaign.Rule), ReadFields = [nameof(Campaign.DiscountPercent)])]
public class ProductDiscountCalculation : IVoxCalculation<Product>
{
public async Task CalculateAsync(Product product, Product result, IVoxCalculationContext context,
CancellationToken cancellationToken)
{
IReadOnlyList<Campaign> campaigns = await context.ReadReachingAsync<Campaign>(cancellationToken);
result.Discount = campaigns.Select(campaign => campaign.DiscountPercent).DefaultIfEmpty(0).Max();
}
}

ReadReachingAsync returns the policy entities in the evaluation's scope whose rule matches the entity as the calculation has it, including what other calculations of the entity set earlier in the same pass. It records no dependency on each policy entity; the reach covers them. A calculation that calls it for a policy type it declares no reach for fails, so a read can't go stale without anyone noticing.

The selector's target is the calculation's entity type or the base type of its family. A reach doesn't follow relations: a campaign over products can't reach a calculation of their variants. When the variants need the campaigns, let a product calculation list the campaigns that reach the product in a calculated field, and let the variants read that list with ordinary tracked reads. The policy type must be dependency tracked, not transient, and expected to be small or medium, see [VoxExpectedCount], since every process keeps its published entities in memory with a compiled matcher per rule. Vox refuses to start when a reach breaks any of these rules or names a field that doesn't exist.

Which changes queue the reach​

Without ReadFields, any change of a policy entity calculates what it reaches: creating, changing, publishing, unpublishing or deleting it. With ReadFields, only a change of the rule or of a listed field does, so an editor who changes a campaign's description or images calculates nothing. ReadFields = [] means the calculation reads nothing but the rule. The entities ReadReachingAsync returns enforce the list: reading a field outside the rule, id and ReadFields, or below them, fails the calculation with an error that names the field.

When a policy entity's change queues its reach, Vox pages through the entities its rule selected before the change or selects after it, by their published values, a page at a time like a recalculation of every entity, shared between the processing hosts. A rule that names a varying field without a context, eg "season is SS26" where the season differs per market, runs once in each market and queues the union. A rule that names a field that's no longer filterable reaches every entity, and matches nothing in ReadReachingAsync, where it's logged as a warning, so one broken rule doesn't stop every calculation.

A change of a policy entity's values in one context, eg its discount in Sweden through a cell of that market, calculates what it reaches in that market only.

The entity's own changes​

A product whose own fields change so that it starts or stops matching a rule, eg its brand changes to Hario, is calculated by its own change, whatever it read the last time: a reached calculation runs when a field that any saved rule over its type uses changes. Vox keeps those fields when rules are saved through the editing APIs, the admin and the MCP server, so save policy entities through them rather than through imports.

Rules returned by code​

When the reach isn't simply a selector property, eg an offer that reaches nothing while it's hidden and every SKU when it has no rule, compute it in a class of the model instead, and declare the reach without a property:

public class OfferReach : IVoxReach<Offer, Sku>
{
public VoxReachResult<Sku> GetReach(Offer offer) => offer.IsHidden
? VoxReachResult<Sku>.Nothing
: offer.SkuRule is { } rule ? VoxReachResult<Sku>.Selected(rule) : VoxReachResult<Sku>.Everything;

public IReadOnlyCollection<string>? ReadFields => [nameof(Offer.Name), nameof(Offer.DiscountPercent)];
}

[VoxReachedBy(typeof(Offer))]
public class SkuOffersCalculation : IVoxCalculation<Sku> { /* ... */ }

Vox finds reach classes among the model's types and creates them once with their public parameterless constructor. A policy type can't have both a selector property and a reach class for the same calculation's entity type, and read fields are given either on the attribute or by the class.

Dependency journal and coalescing​

Entity, relation, membership, and custom dependency changes are appended to one normalized journal, in the transaction of the save that made them. The journal is an outbox: once a save has committed, its changes are dispatched by matching them against the stored dependency graph, and they're removed. Dispatching only committed changes is what makes it correct whatever order concurrent saves commit in. An evaluation stores its dependency on what it reads before it reads it, so either the dispatch of a change finds the dependency, or the evaluation reads the change.

The processing of changes reads this journal directly, in a loop that runs on every processing host of the active deployment, outside the Nexus jobs (see background work): a commit wakes it, and it checks the journal every 30 seconds otherwise, since the journal is the durable record. The hosts share the journal: each claims a bounded part of it, so the pages of a broad change are evaluated by all of them at once. A run dispatches committed changes to the consumers that read them as pages of targets, claims a bounded batch of ready work with a lease, merges every reason to evaluate an entity, evaluates its calculations in the order their reads give, and publishes the settled entities of a batch in one transaction. If five dependencies of one calculation change, the entity is still evaluated once, against current state. The changes that a publication makes are dispatched by the same run, so a chain of calculations across entities continues without a queue in between. There's no Nexus message per calculation or entity.

Newer work with the same stable key replaces pending work. If an earlier generation is already claimed, it keeps its claim and can finish; the newer generation waits separately and subsequent pending saves coalesce there. This normal supersession is logged at Debug, rather than as a lease takeover.

Work is finished only once it's published or durably handed forward, eg as a page of targets, so an interrupted run leaves it to the next one. An ordinary exception is retried within the run before it's a confirmed failure; transient errors (VoxTransientException, database timeouts) are deferred and retried automatically. Calculations that keep changing each other are stopped with an explanation rather than run until they converge.

The stored dependencies are what the admin's Effects tab follows: in a draft or release, the readers of what changed whose stored results differ, a level at a time, see Effects of drafts and releases. A calculation that reads precisely, eg one property of a category rather than the whole entity through a method call, is listed only under what it actually reads, and a draft that changes something else doesn't list it.

Application values that a calculation depends on through DependOnCustom are one more kind of source: like every dependency, it's stored with the results, and a change of the value dispatched while the calculation read is found by the check after its publication, see dependency and change tracking.

The same journal and outbox model drives calculated properties, calculated context memberships, tracked cached references, assessments and entity projection publications. Direct entity projection evaluation is ephemeral and therefore does not create a durable consumer. Source changes and journal/outbox records are committed in the same SQL transaction. Only entity types stored in SQL through Entity Framework take part in calculations: a transient entity type, eg a cart, and so every entity type stored in Redis, has no dependency tracking, so it can't have calculations or be read by one.

Values that change over time​

Prices from dated price list entries, campaigns that start at midnight and offers that end on a Sunday are known before their time comes. A calculation stores them as a VoxTimeline<T>, so the value changes when its time comes without anything running, instead of running again at the boundary with ReevaluateAt.

Say a campaign gives 20% off 10,000 products from 00:00 on 27 November. With a timeline, the 10,000 price calculations run when the campaign is saved, and their prices hold the campaign period from then on. At 00:00, no price calculation runs, and neither does anything that reads the prices. With ReevaluateAt, all of them, and everything that reads them, run at 00:00, and the campaign is fully live only when the last of them has finished.

A timeline is an ordered list of periods, each with an optional start, an optional end and a value:

[
{ "toUtc": "2026-11-27T00:00:00Z", "value": 1299 },
{ "fromUtc": "2026-11-27T00:00:00Z", "toUtc": "2026-12-01T00:00:00Z", "value": 999 },
{ "fromUtc": "2026-12-01T00:00:00Z", "value": 1299 }
]
  • Periods never overlap. Building a timeline from overlapping periods fails with an error that names them. Code that reads overlapping sources, eg two campaigns on the same product, resolves the overlap when it builds the timeline.
  • A time no period covers has no value, a gap. A null value is a gap too, so a period never holds null, and a timeline of a number is written VoxTimeline<decimal>, whose value at a time is a decimal?.
  • Adjacent periods with equal values are merged, so an unchanged result has the same JSON text as the stored one and doesn't wake its readers. Values are equal when their JSON text is, which also covers an object, eg an amount with its currency. A start is inclusive and an end exclusive, and times are UTC instants; the admin shows them in local time.
  • Past periods stay until the calculation stops including them, eg until the price entry or campaign that produced them is removed. Importers should remove price entries and similar rows once they've ended: an ERP import that keeps every historical price makes every timeline, and every reader's copy of it, grow without limit.
// The variant's selling price over time, from its price entries and the campaigns of its product.
var listPrice = VoxTimeline.FromRanges(entries,
entry => entry.ValidFromUtc, entry => entry.ValidToUtc, entry => entry.UnitPrice,
overlap: (a, b) => Math.Min(a, b));
var discount = VoxTimeline.FromRanges(campaigns,
campaign => campaign.StartsAtUtc, campaign => campaign.EndsAtUtc, campaign => campaign.DiscountPercent,
overlap: Math.Max);
// Outside every campaign, percent is null and the list price applies.
result.SellingPrice = listPrice.Combine(discount, (price, percent) => percent == null ? price : price * (1 - percent.Value / 100));

// The member price in December, and the general price outside it.
var memberPrice = VoxTimeline.FromRanges(memberEntries, ...).Or(result.SellingPrice);

// The product's lowest variant price over time; variants without a price at a time are left out of the minimum.
result.FromPrice = VoxTimeline.Combine(variants.Select(variant => variant.SellingPrice), prices => prices.OfType<decimal>().Min());
  • VoxTimeline.FromRanges builds a timeline from rows with validity dates. A row whose value is null is left out, and without an overlap function, overlapping rows fail.
  • Map transforms each value, and is never called for a gap. Combine combines two timelines, and VoxTimeline.Combine many, splitting at every boundary of the inputs; the function gets null for an input with a gap at that time, and is only called where at least one input has a value. A null result is a gap. Or fills the gaps of one timeline from another.
  • timeline.At(instant) gives the value at a time, or null, with no side effects. timeline.NextChangeAfter(instant) gives the next boundary, eg for an assessment's ValidUntil.
  • context.Current(timeline) gives the value at the time the evaluation runs as of, context.EvaluatedAtUtc, and registers the next boundary with ReevaluateAt. It works in calculations, membership calculations, assessments and projections, since they all share IVoxEvaluationContext.

Call Current on the narrowest timeline. ReevaluateAt runs the whole calculation again. A calculation that stores a price timeline, but also calls Current on that timeline to decide whether the variant is purchasable now, runs again at 00:00 on 27 November after all. Call it on a derived timeline instead: context.Current(price.Map(_ => true)) is true wherever there's a price and null elsewhere, and since adjacent equal periods are merged, a campaign that changes the amount but not whether there is one registers no boundary.

Where a timeline can be used. A timeline can be a calculated field, or sit anywhere inside a calculated value: in a VoxVarying, eg VoxVarying<Market, VoxTimeline<decimal>>, in a list, a dictionary or an object. It can also be imported, eg a price schedule sent by an ERP or a timeline mirrored from another Vox application, and on a transient entity type it's just a JSON value. Startup fails with an error that says why for:

  • an owned timeline, or one inside an owned value: editors author the sources, eg price entries and campaigns with their dates, and there's no editor for periods;
  • [VoxFilterable], [VoxSortable], [VoxSearchable] or [VoxUnique] on a timeline or inside it, since its value changes without a write. A storefront that filters or sorts by the current price gets it from a projection or search document that resolves it with Current;
  • a timeline whose values hold a VoxVarying, an entity reference or VoxProjectionRef, VoxRichText, field or attribute values, another timeline or a [VoxSensitive] property. A timeline holds plain values: numbers, strings, flags, enums or simple objects of those. A timeline field as a whole can be [VoxSensitive].

A timeline has no context of its own: one that differs per market is stored per market like any other value, eg in a VoxVarying<Market, VoxTimeline<decimal>>. Reading a timeline records a dependency on the whole field, so a change of a future period reaches its readers. It's part of drafts, releases and history like any other value, and History and Effects compare it period by period.

At the end of the chain, a projection chooses per field: resolve the value with context.Current(...), so the document has today's value and the projection runs again at the boundary, or publish the timeline, so the consumer picks the value by time and nothing runs at the boundary. A storefront reads a published timeline with valueAt(timeline, date) and periodAt from @commerce-mind/vox-web, eg to show "999 kr until 1 December"; @commerce-mind/vox-client has the same helpers. /api/entity-types reports a timeline field with the type Timeline and its values as its item, and the portable entity contract gives another Vox application's generated class a VoxTimeline<T> property.

Results at chosen keys​

Retail data often says which customers or markets a value is for in its rows rather than in variations: an ERP sends a price list per customer group, and the calculation sees the member price as a row with a customer group reference. A calculation can set the values of its own fields at keys of contexts it chooses from such rows, next to its general result, without the model declaring the context types the field varies by:

// The consumer prices in general, and the prices of each customer group at the group's key
result.Prices = Prices(retailEntries, campaigns);
foreach (var group in groupEntries.GroupBy(entry => entry.PriceList.CustomerGroup.Id))
{
context.AtKey<ProductVariant>(VoxCellKey.Baseline.With(nameof(CustomerGroup), group.Key))
.Set(values => values.Prices, Prices(group, campaigns));
}

A read with the member group selected gets the member prices; every other selection gets the general prices, or a less specific key's, by the usual precedence: the more specific key wins, then the context stacking order. A variant's calculation can set member and B2B prices this way.

  • The selector names the field. It must name a calculated field of the calculation, eg values => values.Prices, or a calculated field inside an object, eg values => values.Offer.Price. Anything else, eg an item of a list or a field another calculation sets, fails the run with an error that names it. Null is a value: the field is null at the key.
  • Each run is complete. The keys a run sets replace those of its previous run. A key it no longer sets loses the calculation's values there, eg the member price disappears when its price list is removed.
  • One run, one set of reads. The keys are written by the run at the general address of the scope: published content, a draft or a release. What that run reads is its dependencies, so a change of a group's price list runs it once and rewrites all its keys. There are no runs per key.
  • The general run owns the keys. A calculation is still evaluated at other keys when something it reads has a variation there, eg a Swedish title of a campaign. Such a run ignores AtKey, and its result never replaces a value set at a key. So keyed values are calculated from the general reads: if a member price really depends on a Swedish variation of its inputs, a reader in Sweden still gets the price the general run set. Where a variation key and a chosen key are equally specific, eg Language=sv and CustomerGroup=member, the stacking order decides which value a reader with both selected gets. When the calculation stops setting a key, it runs there once, so a result it has at the key from a variation of what it reads takes the keyed value's place.
  • Keys name existing members. A key naming a member that doesn't exist is skipped with a warning in the log, and the rest of the run is stored as usual. The run records the members of its keys as dependencies, so creating the member runs it again and the key appears. Deleting a member removes the values keyed by it.
  • Not every field can vary. A field that filters, sorting, search or uniqueness read, or that has one inside it, can't be set at a key, since filters and sorting would only see the general value; neither can a VoxVarying field. Setting one fails the run with an error that names it, and so does AtKey in a [VoxRunsPerContext] calculation, whose fields all vary on their own contexts.
  • Drafts and releases. A run in a draft or release writes its keys there, so its Effects and previews show them, and they're published with it.
  • No history at keys. As for other values at keys, only the entity's general content is versioned, so "what was the member price last week" can't be answered from history.
  • Projections. A publication that publishes KeyedCells finds keyed values among the cells of what the projection read, eg a cell for CustomerGroup=member, while one per combination has a document at every member anyway. It must enumerate every context type of the key: one that enumerates only Market drops the key Market=se|CustomerGroup=member rather than cutting it down to Market=se. See Entity projections.

Only the readers of a keyed field run at its key, see Where consumers run: the product's from price, which reads the variants' prices, runs at CustomerGroup=member and gets a member from price of its own there, while a calculation that reads only the variants' names doesn't. The calculation that set the key is never run there for its own keys. This is why it's better to calculate a variant's availability in the same calculation as its prices: a separate availability calculation that read the prices would run at every key too, and so would everything that reads the availability, for a result that's the same at every key.

What keys cost. Every key is a cell, and every read of the entity, in any selection, loads all its cells, as every write of it does. Every reader of a keyed field runs once more per key and keeps its dependencies there, also downstream: the product's from price gets values of its own at each key, so the readers of that field run at each key too. With 3 customer groups in 5 markets, that's 15 keys, and a change of the variant runs the readers of its prices 16 times instead of once. So chosen keys are for a handful of keys per entity. Choose keys that follow the shape of the data: when prices are already a list per market, the keys are the customer group alone, two per variant rather than one per market and group. A model with hundreds of keys per entity, eg a price per store, uses a VoxVarying field instead, eg VoxVarying<Store, VoxTimeline<decimal>>, at the cost of declaring the dimension.

Time dependencies​

Call context.ReevaluateAt(instant) whenever time passing can change the result in a way a timeline can't express. Vox keeps the earliest future instant requested during the run and schedules a durable recalculation for it, even if the current calculated values did not change. During that future run, register the next boundary again if one remains.

Local DateTime values are converted to UTC, unspecified values are interpreted as UTC, and instants at or before context.EvaluatedAtUtc, the time the evaluation runs as of, are ignored. For a calculation that's the time its TimeProvider gives; for a projection, membership calculation or assessment, the start of its evaluation. Use an injected TimeProvider, so boundary behavior can be tested deterministically.

Calculated context memberships use the same dependency and scheduling model without writing a property on the entity. See Languages, markets and channels for inherited and calculation-only candidates.

Cached forward and inverse references are maintained by an internal aggregate calculation per owner entity type. They use the same dependency mechanism and appear as CachedReference entries in /api/calculations. An attribute can instead make a reference refresh on load, after a maximum age or custom policy, or only through IVoxCachedReferenceRefresher. Those modes deliberately do not register target dependencies; see Entities and relations.