Entity projections
Entity projections turn a Vox entity into an application-facing .NET type. They are useful as the content-delivery model for a frontend, as the representation of an entity referenced by rich text or another projection, and as the document published to a search index, feed, cache, or export.
For the team workflow, see Give each channel the data it needs.
Vox.Routing is one durable publication consumer. Route factories publish full paths after reading
parent entities and settings through the projection context. Paths therefore do not need to be calculated fields on
entities: changing an ancestor republishes affected descendants without changing their versions or history.
Several applications can project the same authoritative entity into different contracts. A storefront, an internal tool and a partner API can each receive the shape appropriate to its job without creating three independent domain models or copies that must be synchronized with one another.
When a projection is published durably, Vox records the entities, relations, memberships and other dependencies its factory reads. A source change can then republish only the affected outputs instead of rebuilding every channel document. See Dependency and change tracking.
A projection does not change or get stored on its source entity. It is deliberately different from a cached reference, which stores a small subset of a referenced entity on the entity that owns the relation.
Define projections
One entity type can have several projections. For example, a product can have a full projection for its product page and a smaller card projection for menus, search results, page blocks, and rich text:
public record ProductPage(
string Id,
string Name,
string Description,
decimal Price);
[VoxEntityProjection("product-page", "1", IsDefault = true)]
public class ProductPageProjection
: IVoxEntityProjectionFactory<Product, ProductPage>
{
public Task<ProductPage?> ProjectAsync(
Product product,
IVoxEntityProjectionContext context,
CancellationToken cancellationToken)
{
return Task.FromResult<ProductPage?>(new(
product.Id,
product.Name,
product.Description,
product.Price));
}
}
public record ProductCard(string Id, string Name, string Url);
[VoxEntityProjection("product-card", "1", IsDefaultForReferences = true)]
public class ProductCardProjection
: IVoxEntityProjectionFactory<Product, ProductCard>
{
public Task<ProductCard?> ProjectAsync(
Product product,
IVoxEntityProjectionContext context,
CancellationToken cancellationToken)
{
return Task.FromResult<ProductCard?>(new(
product.Id,
product.Name,
$"/products/{product.Id}"));
}
}
The name is stable and unique within the source entity type. The version describes the output contract and mapping;
change it when either changes. A factory returns one value or null. A collection of entities in different contexts
is composed outside the factory by invoking it once for each entity and context.
Projection output may contain ordinary values, collections, nested output models, and VoxRichText, but not Vox
entity types. Map entities to explicit output types so a projection cannot accidentally expose the complete stored
model.
The projection context is an IVoxEvaluationContext: read other entities, relations, memberships, tracked queries and
Accumulator balances, and declare custom dependencies, through it, eg context.GetAsync<Brand>(...). Those reads are
tracked when the projection is used by a durable publication. context.Contexts contains the caller's context
selection.
Timelines in documents
A projection chooses per field what to do with a timeline, eg a variant's price over time:
- Resolve it with
context.Current(timeline): the document has today's value, and a durable publication runs the projection again at the next boundary. A product card or search document that sorts and filters by price does this. - Publish it as a
VoxTimeline<T>property of the document: the consumer picks the value by time, eg withvalueAtandperiodAtfrom@commerce-mind/vox-web, and nothing runs at the boundary. A product page that shows "999 kr until 1 December" does this.
References to other projections
A projection includes the projections of related entities by reference, never by value. A product page that shows the cards of its accessories holds references to their card projections:
public record ProductPage(
string Id,
string Name,
IReadOnlyList<VoxProjectionRef<ProductCard>> Accessories);
public Task<ProductPage?> ProjectAsync(
Product product,
IVoxEntityProjectionContext context,
CancellationToken cancellationToken)
{
return Task.FromResult<ProductPage?>(new(
product.Id,
product.Name,
product.Accessories.Select(context.Reference<ProductCard>).ToList()));
}
context.Reference<TProjection> takes a VoxReference<T>, or an entity type and ID, and returns a reference to the
target's projection with the output TProjection. A projection hint on a VoxEntityProjectionReference<T>, or an
explicit name, selects one by name. context.Reference(reference) returns a VoxProjectionRef<object> selected by the
hint, a selection or the reference default. An entity family whose kinds project to different outputs has one projection
with a factory per kind, which a reference names by its shared output, see
Projections per kind of an entity family. Nothing is evaluated: a
reference is serialized as the key of the referenced projection, eg
{ "$projection": "vox://entity/Product/a1?projection=card" }. A reader looks the projection up by it in the
projections of a graph, or reads the entity type, ID, projection and contexts from it with the client's
parseProjectionKey or .NET's VoxProjectionRef.TryParseKey. The referenced projection's version is on its node in
the graph.
A factory never sees the value of another projection. Data a projection needs for its own logic, such as the cheapest accessory's price for sorting, is read from the entities through the projection context. This keeps every projection independently evaluated, published, cached and invalidated:
- A reference depends on whether the referenced entity exists, not on what its projection reads. Changing an accessory's name republishes the accessory's card, not every product that references it.
- Changing which entities a product references, or deleting a referenced entity, republishes the product.
Whoever reads a projection decides whether its references are materialized:
- Direct delivery and preview materialize the graph in Vox, in the request's selection, so a draft or release preview shows the draft or release of every entity in it (see below).
- Durable publication never materializes. It publishes one projection at a time and lists its references, and a delivery system resolves them when they're read, eg Vox Serve.
IVoxEntityProjectionEvaluator.EvaluateAsync evaluates one projection and leaves its references unresolved.
MaterializeAsync evaluates the projection and the ones it references, level by level, into a
VoxEntityProjectionGraph: the root's key and every projection by key, each evaluated once however often it's
referenced, so cycles stay finite. Its VoxProjectionMaterializationOptions limit the levels of references, the
number of projections and the output size. A reference that can't be materialized, eg to a missing entity, stays in
the document and gets a diagnostic. Entities embedded in rich text are references too, and are materialized into the
same graph (see Rich text and entity references).
Projections per kind of an entity family
The kinds of an entity family have fields of their own, so each kind usually needs a projection of its own. Take CMS blocks: an image-and-text block becomes an image, a heading and a body, while a products block becomes a heading and a list of product cards. Write a factory per kind under one projection name, and Vox projects each block with the factory of its kind:
public abstract record BlockView(string Name);
public record ImageTextBlockView(string Name, VoxImageDescriptor? Image, string? Heading, VoxRichText? Body) : BlockView(Name);
public record ProductsBlockView(string Name, string? Heading, IReadOnlyList<VoxProjectionRef<ProductCard>> Products)
: BlockView(Name);
// The settings every factory of the projection shares
[VoxEntityProjection("block", "1", IsDefaultForReferences = true)]
public abstract class BlockProjection;
public class ImageTextBlockProjection : BlockProjection, IVoxEntityProjectionFactory<ImageTextBlock, ImageTextBlockView> { ... }
public class ProductsBlockProjection : BlockProjection, IVoxEntityProjectionFactory<ProductsBlock, ProductsBlockView> { ... }
// Optional: the kinds without a factory of their own, eg text blocks
public class CmsBlockProjection : BlockProjection, IVoxEntityProjectionFactory<CmsBlock, BlockView> { ... }
Together they're one projection, ContentBlock/block. A page references it without knowing the kinds of its
blocks: page.Blocks.Select(context.Reference<BlockView>). An entity type that isn't a family has one factory per
projection, as before.
Which factory projects an entity. The factory of the most specific class the entity is: an image-and-text block
uses ImageTextBlockProjection, and a text block, which has no factory of its own, uses CmsBlockProjection. A factory
can also be written for an abstract class between the family and its kinds, eg a MediaBlock that image and video
blocks extend, and projects the kinds below it that have no factory of their own. Each factory only ever receives
entities of its class.
A kind without a factory has no value. A projection doesn't have to cover every kind; a bundle-contents
projection of bundles only is legitimate. An entity of a kind that no factory covers is treated like a factory that
returned null: a direct request for it returns 404, a reference to it gets the diagnostic ContentBlock 'b9' is of the kind 'video', which has no 'block' projection., and a publication publishes no document for it, without an error.
Rich-text validation doesn't read the embedded entities, so a block of an uncovered kind embedded in rich text shows up
as that diagnostic when the text is delivered. Startup doesn't check that every kind is covered.
Shared settings. The factories of a projection share its name, version, display name, root and reference defaults,
AllowContentDelivery and its publication: either every factory has [VoxEntityProjectionPublication], with the same
settings, or none has. Write them once on an abstract base class, as above; both attributes are inherited, and a class
without a factory interface isn't a factory itself. Writing them on every factory works too. Startup fails when the
factories disagree, eg The factories of ContentBlock/block disagree on AllowContentDelivery: ..., and when two
factories of one projection are for the same class. Only BatchSize can differ: a factory that declares its own
[VoxEntityProjection] replaces the base class's, repeats the shared settings and sets its own batch size. Each factory
keeps its own batch step and preloading, which run for its own entities.
One version. When the output of one kind changes, raise the projection's version: its contract as consumers see it has changed. As for any projection, the version doesn't start a full build of a publication; sources are republished as they change, or a full build is requested, which covers every kind.
The shared output. References, sinks and the schema use one output type, which Vox derives from the factories'
outputs: the most specific base class they all share other than object, eg BlockView, or else the one interface
they all implement. Outputs that share neither fail at startup; give them a shared base record. A projection with one
factory, eg of one kind, has that factory's output. A reference uses the shared type: VoxProjectionRef<BlockView>,
not VoxProjectionRef<ImageTextBlockView>, which startup refuses with a message naming the shared type. A relation
restricted to one kind, eg VoxReference<ImageTextBlock>, is referenced the same way, with
context.Reference<BlockView>(block.Hero).
The kind is delivered. Every delivered projection of a family's entity has a kind next to its entityType, on the
root of a response and on each of its projections, so a storefront can render each block with a component per kind.
It's left out for entity types that aren't families. A published document has the kind in
VoxEntityProjectionPublicationChange<T>.EntityKind. A projection reference and a rich-text reference don't carry the
kind, since creating a reference doesn't read the referenced entity; a consumer resolves the reference to its delivered
projection, which has it:
"vox://entity/ContentBlock/b7?projection=block": {
"entityType": "ContentBlock", "kind": "image-text", "entityId": "b7", "projection": "block", "version": "1",
"value": { "name": "Autumn jackets", "image": { ... }, "heading": "...", "body": "..." }
}
The value is the output of its kind's factory, with the kind's properties. The schema,
GET /api/entity-projections/schema, lists each projection's implementations with the kinds each projects, the JSON
schema of its output and its references, so a GraphQL schema can make a union of the kinds' outputs.
Batch loading
A factory that shows data from another system, eg the rating and number of reviews of each product from a review system, can load it for many entities in one call with a batch step:
public record ProductReviews(decimal? AverageRating, int Count);
public record ProductSearchDocument(string Id, string Name, decimal? AverageRating, int ReviewCount);
[VoxEntityProjection("product-search", "1", BatchSize = 100)]
public class ProductSearchProjection(IReviewClient reviews)
: IVoxEntityProjectionFactory<Product, ProductSearchDocument, ProductReviews>
{
public async Task<IReadOnlyDictionary<string, ProductReviews>> LoadAsync(
IReadOnlyList<Product> products,
IVoxEntityProjectionBatchContext context,
CancellationToken cancellationToken)
{
// One call to the review system for the whole batch
var byProduct = await reviews.GetSummariesAsync(products.Select(product => product.Id).ToArray(), cancellationToken);
foreach (var product in products)
{
var entry = context.For(product);
entry.Dependencies.DependOnCustom("product-reviews", product.Id);
if (byProduct.GetValueOrDefault(product.Id)?.CampaignEndsAtUtc is { } endsAt)
{
entry.ReevaluateAt(endsAt);
}
}
return products.ToDictionary(product => product.Id, product =>
byProduct.GetValueOrDefault(product.Id) is { } summary
? new ProductReviews(summary.AverageRating, summary.Count)
: new ProductReviews(null, 0));
}
public Task<ProductSearchDocument?> ProjectAsync(
Product product,
ProductReviews? reviews,
IVoxEntityProjectionContext context,
CancellationToken cancellationToken)
{
return Task.FromResult<ProductSearchDocument?>(
new(product.Id, product.Name, reviews?.AverageRating, reviews?.Count ?? 0));
}
}
LoadAsync returns the data by entity ID, and each ProjectAsync gets its part. Vox projects the entities of one
projection together where it can, at most BatchSize at a time:
- Materialization evaluates the graph breadth first, grouping the projections at each level by type. A product with
three accessories is two batches: the product, then the three accessory cards in one
LoadAsync. - Durable publication runs one
LoadAsyncper batch of a page of sources.
What a batch step depends on
A batch step declares what the data it loads depends on, so that a durable publication publishes the right documents again when that data changes. It declares either for one entity or for the whole batch:
- For one entity, through
context.For(entity): itsDependenciesandReevaluateAtapply to that entity's document only. In the example, when the review integration publishes("product-reviews", "P1")withIVoxDependencyChangePublisher, only P1's document is published again, and a campaign that ends tomorrow publishes only its own product again then. The entity must be one of the batch:ForthrowsArgumentExceptionfor any other, also for an entity of another type with the ID of one in the batch. - For the whole batch, through
context.ForAll: what it declares, egcontext.ForAll.Dependencies.DependOnCustom("exchange-rate", "EUR/SEK"), and acontext.ForAll.ReevaluateAt, apply to every entity of the batch, and so does every read throughcontext.ForAll, eg of a related entity. Use it for data that every document of the batch shows.
A dependency declared in ProjectAsync, through its context, is a dependency of that entity only too.
Declare in LoadAsync when that's where the code knows the keys, eg the IDs the review system returns. Reads of the
entities' own properties in LoadAsync are dependencies of each entity.
Declaring before or after the load is equally safe. The dependencies of a page are stored when the page finishes, and once it has committed, Vox checks them against the changes dispatched since the page started reading, so a review that arrives while the batch step loads still publishes its product again (see dependency and change tracking).
A batch step reads the tracked Accumulator
balances of its own entities with context.GetBalancesAsync, which makes each balance a dependency of its own entity
only, so a stock change of one position publishes that position again:
var onHand = await context.GetBalancesAsync(StockPosition.OnHand, positions, cancellationToken);
The keyed form, context.GetBalancesAsync(accumulator, entity, keys), reads the balances of one entity at keys.
context.ForAll.GetBalancesAsync(...) works in a batch step too, but its balances are dependencies of every
entity of the batch.
Both forms also take an expression, for a threshold read that publishes a coarse value, eg "few left", and publishes the entity again only when its stock crosses a threshold rather than on every change:
var levels = await context.GetBalancesAsync(StockPosition.OnHand, positions,
stock => stock <= 0 ? "out" : stock <= 5 ? "few-left" : "in-stock", cancellationToken);
Data of related entities, eg the stock of each product's variants, is loaded by the batch step as well. It reads the
relations through context.ForAll, which are dependencies of the whole batch, and declares each external key for
the entity whose document shows it, eg
accumulators.ReadTracked(context.For(product).Dependencies, StockPosition.OnHand, positionId) with an injected
IVoxAccumulators, before reading the balances with accumulators.GetManyAsync. A threshold read of them declares and
reads in one call, accumulators.GetTrackedAsync(context.For(product).Dependencies, StockPosition.OnHand, positionIds, expression).
Preloading
A projection reads related entities with the ordinary APIs, eg await product.Variants.LoadAsync(). To read them
for many sources at once, a factory declares what it reads, and Vox reads it for a page of sources into the
operation's read cache scope before projecting them. The projection and its helpers don't change: their reads are
answered from the scope.
public class ProductVariantsProjection
: IVoxEntityProjectionFactory<Product, ProductVariantsDocument>, IVoxEntityProjectionPreloading<Product>
{
public void ConfigurePreloading(IVoxPreloadBuilder<Product> preload)
{
preload.Include(product => product.Variants).ThenInclude(variant => variant.Positions);
}
public async Task<ProductVariantsDocument?> ProjectAsync(Product product, IVoxEntityProjectionContext context,
CancellationToken cancellationToken)
{
var variants = await product.Variants.LoadAsync(cancellationToken);
return new ProductVariantsDocument(product.Id, variants.Count);
}
}
A declaration is a hint. What the projection reads that wasn't preloaded is read when it's read, and only what it
actually reads becomes its dependencies. A publication also preloads what each source read in its previous run, from
its stored dependencies, so a factory without declarations gets most of the benefit from the second run on. When what
to read depends on the data, eg IDs in a property that no relation has, implement IVoxEntityProjectionPreloader<TEntity>
and preload through its context (IncludeAsync, PreloadEntitiesAsync).
A preloaded read is safe for every source that reads it: the sources' dependencies are stored with the page, and once the page has committed, Vox checks them against the changes dispatched since the page started reading, so a change that was saved meanwhile still publishes them again (see dependency and change tracking).
Defaults and explicit selection
Root requests and references have separate defaults because a full page model is rarely a safe nested model:
IsDefault = trueselects the projection for a direct/root request.IsDefaultForReferences = trueselects the projection when another projection or rich-text value references the entity.- An explicit projection name or output CLR type always wins.
- If an entity has only one projection, it is used for both cases.
- If no reference default is declared and exactly one projection is not the root default, Vox uses that projection for references. This avoids accidentally nesting the full projection.
- Any remaining ambiguity is an error. Vox never guesses between several full or compact representations.
There can be at most one root default and one reference default for an entity type.
Direct content delivery
Entity projections can be the API model consumed directly by an application:
GET /api/products/p123/projection
GET /api/products/p123/projection/product-card
For singleton entity types, omit the ID: /api/commerce-settings/projection selects the root default and
/api/commerce-settings/projection/{projectionName} selects a named projection. An absent singleton returns 404.
The first route selects the root default. The second selects a projection by name. The response identifies the source
entity, with its kind for an entity family, selected projection and version, the scope and selection it was
resolved in, eg draft and a language, and contains the projected value and its key.
It's materialized: projections holds the projections it references, and the ones they reference, by key, with
aliases for rich-text references without a projection and diagnostics for references that couldn't be
materialized. Normal entity read permissions apply to every projection in the graph, and a projection of an entity the
caller can't read is left out with a diagnostic.
A projection's values are redacted by [VoxSensitive] on the projection class itself, not by the entity fields it was
built from. A projection that copies a sensitive purchase price into an unmarked property exposes it to everyone who
reads the projection, so mark that property, or anything derived from it such as a margin, with the same
classification, see sensitive fields.
Projection reads accept the same content and context query parameters as entity reads, together with
richTextFormat=Json|Html (the rich-text document by default) and referenceDepth, the levels of references to materialize, 8 by default and 0 for the
projection alone. Set AllowContentDelivery = false on VoxEntityProjectionAttribute for a projection that must
only be used internally or published to a sink. A projection for content delivery can't reference projections that
aren't, since its graph couldn't include them.
Direct evaluation is ephemeral. It reads the requested published, draft, or release content for every projection in
the graph, but does not persist dependencies, publication state, or assessments produced through
context.Assessments.
Direct delivery returns the shape the projection builds. Request stages, which fill in what only a request can know, eg the products a recommendation engine picks for a visitor, run only in Vox Serve, so a block of recommended products is delivered here without its products.
Source maps
POST /api/entity-projections/source-maps, and IVoxProjectionSourceMapper in .NET, tell what the values of
projections came from: for each path of a projection's value, eg products[2].name, the entity and field it was read
from, eg Brand, b-12, name, and the member of a varying value, eg Language=sv. The admin uses them to edit what
an editor selects on a previewed page, without any declarations in the projection. Vox computes them only when they're
asked for, by evaluating the projection once with its reads recorded and finding the recorded values in its output. See
Visual preview for how values are matched and the limits.
References and projection hints
An ordinary Vox relation can carry a projection hint without becoming a different kind of relation. This is useful for ordered CMS structures such as a page sidebar whose blocks can also be used by other pages:
public interface IPageBlock : IVoxEntityBase
{
}
public class Page : IVoxEntity
{
public virtual List<VoxEntityProjectionReference<IPageBlock>> Sidebar { get; set; } = [];
}
page.Sidebar.Add(new VoxEntityProjectionReference<IPageBlock>(
"summer-hero",
"HeroBlock",
"page-section"));
The entity type and ID are the relation identity. Projection is only a delivery hint, which context.Reference
honors when a projection references the block: page.Sidebar.Select(block => context.Reference(block)). The relation
remains queryable and indexed like any other Vox relation. Rich text uses the same projections and selection rules; see
Rich text and entity references.
Optional publication
Add VoxEntityProjectionPublication when the same projection should also be maintained in an external system:
public record ProductSearchDocument(
string Id,
string Sku,
IReadOnlyDictionary<string, string> Names);
[VoxEntityProjection("product-search", "1", IsDefault = true)]
[VoxEntityProjectionPublication]
public class ProductSearchProjection
: IVoxEntityProjectionFactory<Product, ProductSearchDocument>
{
public Task<ProductSearchDocument?> ProjectAsync(
Product product,
IVoxEntityProjectionContext context,
CancellationToken cancellationToken)
{
return Task.FromResult<ProductSearchDocument?>(new(
product.Id,
product.Sku,
product.Names));
}
}
A published projection needs at least one IVoxEntityProjectionPublicationSink<TProjection>. Its session receives
pages of upserts and deletes through WriteAsync; CompleteAsync is the external commit point. Delivery is at least
once, so sinks should be idempotent by source entity ID. A failed sink leaves the source pending for retry without
blocking entity saves, settlement, or events.
The sink of a projection of an entity family is typed with its shared output, eg
IVoxEntityProjectionPublicationSink<BlockView>, while each document's Projection holds its kind's output, eg an
ImageTextBlockView, and EntityKind says which kind it is, see
Projections per kind of an entity family. Serialize a document by its
runtime type, JsonSerializer.Serialize(change.Projection, change.Projection.GetType()), since serializing it as
BlockView drops the kind's properties.
Every sink has a stable key, which Vox keeps what the sink has published under, and display data for the API and MCP:
[VoxPublicationSink("algolia-products", DisplayName = "Algolia product search",
Description = "Product cards for the storefront's search page")]
public class AlgoliaProductSink : IVoxEntityProjectionPublicationSink<ProductSearchDocument> { ... }
A sink may make each page visible as it receives it, or hold the pages until CompleteAsync; Vox doesn't need it to
be all or nothing. It must accept the same upserts and deletes again: an upsert of a document it already has replaces
it, and a delete of a document it doesn't have succeeds. A build that fails is replayed rather than resumed, see
Failures and replay, so a sink that streams pages can see a document of a failed build that a
later build deletes.
Publication never materializes references. Each upsert lists the document's References, its VoxProjectionRefs and
the entities embedded in its rich text, so a sink can store the edges of the graph without reading the document. A
delivery system then resolves a reference when it's read, eg with a GraphQL field resolver that looks up the document
by entity type, ID and projection. Vox Serve is Vox's own such delivery system. Every projection a
published projection references must be published too, so the references point to documents a sink receives; Vox
checks this at startup.
GET /api/entity-projections/schema, and IVoxEntityProjectionSchemaProvider in .NET, describe the projections of
the model for such a delivery system: each projection's key, version, whether it's published, the JSON schema of its
output and the properties that reference other projections, with the projections they can reference. isRootDefault
and isReferenceDefault say whether it's the projection that a read of its entity type, or a rich-text reference
without a projection, gets when it names none. They're the effective defaults, with the fallbacks of
Defaults and explicit selection, eg an entity type's only projection is both.
A publication factory may also explain an omitted or degraded output with an assessment:
var publication = context.Assessments.For<ProductPublicationDefinition>();
if (product.Names.Count == 0)
{
publication.Finding(definition => definition.MissingRequiredContent)
.Add("The product has no publishable name.", "content.name");
publication.SetOutcome(VoxAssessmentOutcome.Fail);
return null;
}
publication.SetOutcome(VoxAssessmentOutcome.Pass);
return new ProductSearchDocument(product.Id, product.Sku, product.Names);
These results are persisted once a page of sources has been written to the publication's sinks, so a build keeps none
of them in memory; those of a build whose sink fails later are kept until the source is published again. A source is
evaluated once for every sink of its publication, so it has one result however many sinks there are. A failed factory
or sink marks the producer-owned assessment
as Error while retaining its previous diagnostics. A result produced while the source is projected at a combination
of members, see below, is in the context of those members, limited to the context types its definition declares. A
result by fewer context types than the publication publishes per combination, eg by market in a publication per market
and channel, is produced at several combinations, and the one kept is that of the first combination that produced it,
in the order of the members' ids, eg {Market=se|Channel=app} before {Market=se|Channel=web}. See
Entity assessments.
Several sinks
Register as many sinks for a projection as it has destinations, eg a projection store and a search engine. Each source is evaluated once and written to every sink, and each sink moves at its own pace: when the search engine is down for an hour, the projection store keeps receiving changes. Once the search engine works again, the next run publishes to it every source that changed in that hour, each once, as it is then. It doesn't replay the hour's changes in order: a sink receives each changed source's current document, never the ones in between.
- The key is the sink's identity. Renaming the class keeps what the sink has published. Changing the key makes it a
new sink, which needs a full build. A sink without
[VoxPublicationSink]fails with a message naming its class, and so do two sinks of one publication with the same key. The attribute isn't inherited. A sink registered by type is checked when the application starts; one registered with a factory is checked when its publication first runs, which then fails with the same message while the other publications run. - A lagging sink catches up in the same run. A run first writes what changed to the sinks that are up to date, then each sink that's behind publishes every source that changed since it was last up to date, paged by source. The run holds the publication until the lagging sink has caught up, so after a day's outage of a search engine in which 300,000 products changed, the projection store's next changes wait about as long as an incremental build of 300,000 products takes. That happens once per outage.
- Fail fast. While a sink still fails, each run tries it again and holds the publication for as long as the sink takes to fail, eg a connection timeout. Give a sink short timeouts rather than long retries of its own.
- Adding a sink doesn't fill it. A new sink receives the sources that are still pending for the other sinks and every
later change, but not the rest of the catalog. Request its full build, eg with MCP's
projection_publicationstool, actionrebuildwith itssink, at a time when holding the publication's other sinks is acceptable, see Incremental and full builds. - Removing a sink drops its state. The next run of its publication forgets what it published, so it doesn't hold back the pending work of the others. Only hosts that run publications do this. During a deployment, the old release's processing doesn't know a sink the new release adds, so request its full build once the new release is active, see What the application must do.
Served projections
A projection whose output implements IVoxServedProjection is published to the projection store of
Vox Serve, which serves customer traffic from it, without the application registering a sink for it:
public record ProductCard(string Id, string? Name, decimal? Price) : IVoxServedProjection;
It still needs [VoxEntityProjectionPublication], and the backend calls vox.AddServePublishing(), which registers
Vox Serve's sink, vox-serve, for every served output beside any sinks of the application's own, eg a search engine.
The backend refuses to start, naming the projection, when a served projection has no publication, includes drafts or
releases, has a [VoxSensitive] value, or references a projection that isn't served with a typed
VoxProjectionRef<T>. See Serve a projection.
Enumerating contexts
A projection runs in one of two modes, context.Mode:
- Selected, for content delivery and preview: the caller selects the contexts, and a context type the selection leaves out resolves to its baseline.
- Enumerating, for durable publication: the projection enumerates the context types its selection leaves out, eg to fill a cache with an entry per market.
The enumeration calls behave correctly in both modes, so a projection doesn't branch on the mode:
public async Task<ProductCacheDocument?> ProjectAsync(
Product product, IVoxEntityProjectionContext context, CancellationToken cancellationToken)
{
var entries = new List<ProductCacheEntry>();
// Selected: the selected market, or the baseline. Enumerating: every market the product exists in.
foreach (var market in await context.ExistsInAsync<Market>(product, cancellationToken))
foreach (var language in await context.VariesInAsync<Language>(product, cancellationToken))
{
var narrowed = context.In(market, language);
var resolved = await narrowed.GetAsync<Product>(product.Id, cancellationToken);
entries.Add(new(market.Id, language.Id, resolved?.Name, market.Criteria));
}
return new ProductCacheDocument(product.Id, entries);
}
ExistsInAsync<TContext>: the members the entity exists in, or every member for an entity type without memberships of the context type.VariesInAsync<TContext>: the members the entity has cells for, plus the baseline (IsBaseline).GetKeysAsync: the keys of the entity's cells for some context types, as combinations of members, including{}.In(...): a projection context reading in a narrower selection, the context type of each member replaced by it. It takes one member of a context type at a time, as the calls above give them, and the baseline of a context type only where the projection doesn't read in that type, since a reference created there couldn't carry anything else.
A member carries what the context manifest has of it: its fallbacks, its group and, for a context type selected by criteria, its criteria, so a cache can hold every variant's entry and select between them when it's read. Restricted context types, eg a staff-only experiment, are only enumerated when the publication includes them.
Enumerations are dependencies: when a product gets its first {Language=de} cell, or starts to exist in a market, the
documents that enumerated them are published again. Reads inside In(...) are dependencies at the key of its members.
A reference created through a narrowed context carries its members in its key, eg
vox://entity/Product/a1?projection=card&context=Market:no, and is resolved in them on top of the reader's selection,
so references to a projection in different contexts are different projections of a graph. The client's
getProjectionKey builds the same keys, eg for a rich-text reference with a projection.
Publishing per context
Durable publication reads published content and evaluates in enumerating mode. A publication can also enumerate context types itself, in one of two shapes per context type:
[VoxEntityProjection("product-cards", "1")]
[VoxEntityProjectionPublication(
PerCombination = [typeof(Market)],
KeyedCells = [typeof(Language)],
IncludeDrafts = true)]
public class ProductCardProjection : IVoxEntityProjectionFactory<Product, ProductCard> { ... }
- Per combination: a document per combination of members where the source is read, eg
p1?Market=noat the key{Market=no}, and none without a market. This suits search engines with a record per market or language, which can't pick the most specific key when they're queried. - Keyed cells: the values of a document per key in its
Cells, eg itsnameat{}and at{Language=sv}, by the paths ofVoxDocumentPaths. A cell at a more specific key only has the values that differ there.
A document at every member where the source is read
A context type published per combination gives a document at every member where the source is read, with that member selected:
- A context type the entity type isn't a member of gives a document at every member. With four languages, every product has four documents.
- A context type it's a member of, eg
Market, orLanguagewhen products are members of the languages they have names in, gives a document at every member the source is a member of, and at every member that falls back to one of them. Take the languagessv,fi, which falls back tosv,enandda, and a product with a Swedish and an English name: it has documents atsv,fianden. The Finnish document has the Swedish name, as a read in Finnish would. A product that's in no market has no documents in a publication per market.
Several context types give every full combination: a product in 5 markets and 3 channels has 15 documents, and a
context type with 300 members gives 300 documents per source. Each combination is evaluated separately, so choose
PerCombination for the context types a target really keeps a record per member of, and publish other context types
as keyed cells. A build holds fewer sources at a time the more combinations its per-combination context types have, so
such a publication takes longer to build while each page holds about as many evaluations; the members of keyed cells
don't make the pages smaller.
Each document says in OwnValuesIn which context types of its key have cells of their own at its member, not only at
the member's fallbacks, so a target can tell "the Finnish document has a Finnish name" from "the Finnish document only
has what Finnish falls back to":
| Product | Document | OwnValuesIn |
|---|---|---|
| Has a Finnish name | p1?Language=fi | ["Language"] |
| Has only a Swedish name | p1?Language=fi | []: its name comes from Swedish through the fallback |
| Has only a Swedish name | p1?Language=sv | ["Language"] |
Memberships count: a product with an existence cell of its own at se, written, inherited or derived from its values,
has ["Market"] there, while one in se-b2b only through its fallback to se doesn't. OwnValuesIn sees the source
whole and what the projection read in published content without a member selected, so a cell of a source field the
projection doesn't output counts, while something the projection reads only at one member, or a value its code derives
from the selected member, doesn't.
The members and their fallbacks come from the context manifest. A new member, a removed one or a changed fallback changes the documents of every source without any of their cells changing, so it's published by the next full build, see Incremental and full builds. Until then, the documents stay as they were.
Keyed cells and the members found in cells
The members of a context type published as keyed cells are those where what the projection read has cells, combined with the baseline. A cell of another entity the projection read counts only when it has a value of a field the projection read, as for every consumer, see Where consumers run: a Swedish title of a campaign gives no Swedish cell of a projection that only read the campaign's discount, since it would be the same as the general one. The source entity is read whole, so all its cells count.
Calculated values at keys are cells like any other, including
results at chosen keys, eg a member
price at Market=se|CustomerGroup=member gives a cell at that key. A key counts only when the publication enumerates
every context type of it: one that enumerates only Market drops the key Market=se|CustomerGroup=member entirely
rather than cutting it down to Market=se.
So a projection whose output differs at a member of a keyed-cells context type only through its code, without anything it reads having cells there, eg a hard-coded value per language, has no cell of its own at that member: a delivery system reads the baseline's values there. Keep such values in data, eg a field varying by language, so that publication sees them.
Documents and their existence
Each document has its Scope, Key, MemberOf, the context types it's a member of, and Exists: its membership at a
key with such a context type, and its own existence at the baseline. A document without a projection says that the
source doesn't exist there. It's published only where it hides another document of the source with a projection that a
reader would otherwise reach: one at a member the document's member falls back to, or one of the parent scope. For
example:
- At a member that the source is left out of, explicitly or by a calculation, while the member falls back to one it's
in: a product in
sethat's left out ofse-b2b, which falls back tose, has a document without a projection atse-b2b, so a reader there doesn't fall back to the Swedish document. - At a member where the factory returns null while it returns a projection at a member this one falls back to, eg in Finnish, which falls back to Swedish.
- In a draft or release where the source doesn't exist while its parent scope has a document, eg a product deleted in a release.
A product left out of a market that doesn't fall back to another, or a product that only exists in a draft, simply has
no published document there. A delivery system resolves the documents of a source like the cells of a keyed document, with
VoxEntityProjectionPublicationChange.ToKeyedDocument and VoxKeyedDocumentResolver: the document of the most specific
key that the request's selection matches, where the source exists, and then its cells in the same selection. Every
document carries ManifestRevision, the revision of the context manifest it was built with, which the build has as
Manifest, so a delivery system can tell when its documents and manifest disagree.
The projection schema export lists the context types each publication enumerates in each shape, so a delivery system knows whether to look up a document per combination or to resolve cells.
A publication publishes published content only, unless it opts in with IncludeDrafts or IncludeReleases, eg for a
preview cache, so unfinished work only reaches a sink deliberately. It then publishes the documents of a scope where
they differ from its parent's, at every combination of members that the scope reads, with ids like p1?draft,
p1?release:autumn or p1?draft|Market=no. VoxEntityProjectionPublicationChange.ToAuthoringEnvelope gives them as
the layers of an authoring envelope, which VoxAuthoringComposer composes over the published keyed document before it's
resolved, see Portable contexts. Restricted context types are only
published when the publication includes them with IncludeRestricted.
An IVoxContextManifestPublicationSink receives the context manifest whenever its revision changes, eg when a context
entity, a trait or the stacking order changes. Like a projection sink, it needs [VoxPublicationSink] with a key of its
own, and each manifest sink keeps the revision it published last, so one that fails is retried on its own and doesn't
keep the others from the new manifest.
A publication publishes one document per source and combination. When a target needs a record per variant of a product, publish a projection of the variant entity type, which has a document per variant, or let the sink split the product's document into the records the target needs, eg a search record per variant from a product card that lists its variants.
Incremental and full builds
Published entity, relation, membership, and dependency changes append to the shared dependency journal. Matching source IDs are coalesced into the publication's pending sources before its job evaluates them, so several changed dependencies cause one evaluation of a source rather than one evaluation per change. See Calculations.
Publications are integrations, so they're Nexus jobs, which operators watch, pause and run in the Nexus admin, with
their logs and run history. Each publication has two jobs, named after its key, eg for the publication product-feed of
Product "Product/product-feed incremental" and "Product/product-feed full":
- The incremental job publishes the pending sources to each sink, from where that sink is, see
Several sinks. Vox requests it when the processing of changes adds pending sources, and when a
source is due at a time, see below. It also runs on
VoxOptions.OutboxJobSchedule, every 30 seconds by default, as a fallback, since Nexus doesn't guarantee that a requested start runs at once, and that schedule also retries a sink that failed. While a full build of any sink of the publication is requested, or one was interrupted, it requests the full job instead, since the full build publishes the pending sources too. - The full job rebuilds the sinks whose full build is requested, or every sink of the publication, including the
pending sources. Vox requests it when a full build is requested, eg by a migration's
RebuildPublicationsstep, which rebuilds every sink. After a full build failed, the next run of the incremental job requests it again. An operator can run it from the Nexus admin. Once it completes, it requests the incremental job for the sinks it didn't build.
The two jobs share a Nexus mutex, so an incremental run never overlaps a full build, also across hosts. So a full build of one sink holds the publication's other sinks too: filling a new search index with 2 million product cards stops the projection store from receiving that publication's changes until the search index is filled. Plan full builds of a publication with several sinks like any other full build.
A full build visits every current source and sends each sink it builds the deletes of what that sink has and the build
didn't produce. It's one session per sink, with CompleteAsync called once at the end, so a sink can buffer the build
however it needs, eg by writing to a new index and swapping it in at CompleteAsync; such a sink can ignore the
deletes. Several sinks that need a full build share one: each source is evaluated once and written to all of them.
Vox doesn't decide on its own when a full build is needed. A publication that was never built publishes its pending
sources incrementally, and a new projection version is published incrementally too, source by source as they change.
When the target needs every source in the new version, or the whole catalog on a first build or for a new sink, request
a full build: with a migration's RebuildPublications step, with MCP's projection_publications tool, action
rebuild, for every sink or one sink, or by running the publication's full job in the Nexus admin. The developer who
changed the projection knows whether its documents changed for every source.
The same goes for the members of a context type that a publication publishes per combination: adding a language,
removing a market or changing what a language falls back to publishes nothing by itself. Request a full build when the
change should reach the target, eg after adding German, so every product gets its German document, or after removing a
market, so its documents are deleted. Until then, a source that's published again for another reason gets the documents
of the current members, and the documents of a removed member stay, though no reader selects a removed member. Every
document carries ManifestRevision, so a target can tell which manifest it was built with.
Renamed and removed publications. A publication is named after its entity type and projection, eg Product/feed,
and that name keys what Vox stores for it. When the projection is renamed in code, eg [VoxEntityProjection("feed")]
becomes [VoxEntityProjection("search")], Product/search is a new publication that starts empty: request a full
build of it. A renamed entity type is covered in Model evolution. The
publication that no longer exists, like one whose [VoxEntityProjectionPublication] is removed, keeps what Vox stored
for it. Its documents in the sinks and its routes stay until you remove them. The warnings and other assessments it
produced stay on the entities, since nothing produces them again; they can't be reported over, so removing them means
deleting them from the database. The dependencies it stored stay too, and the changes they match keep one pending
source per source for it. Those are harmless: nothing publishes them, and they don't grow with further changes.
Sources that are due at a time. A source whose projection changes at a future instant, eg a price that becomes
valid at midnight (see ReevaluateAt in batch loading), is kept as a pending source with that due
time. After a run, the job requests its own next start at the earliest due time that's left, and a delayed start is
only requested again when a due time is earlier than the one already requested. So 1,000,000 prices that become valid
at midnight are one requested start of the incremental job, not 1,000,000 timers. A publication that reads a query
field whose storage is still being built after a migration waits, without failing, and its incremental job starts
again a minute later, or at its next scheduled run.
Inspect registered publications and their state with the operator permission vox:Schema:
GET /api/entity-projection-publications
It lists each publication's sinks with their key, display data, how many sources each hasn't published yet, the projection version each was last built with, their builds and their last error. A source that's due later, see above, isn't counted until it's due, so a count of zero means that the sink has nothing to do now. The publication key combines the source entity type and projection name because names are scoped to an entity type.
Pending work and positions
The pending sources of a publication are one journal that its sinks share. A run stamps the pending sources it takes with a position, a number that only grows, and each sink keeps the position it has published up to. A sink that's behind publishes the sources with a later position than its own. Positions follow the order in which changes commit, not the time they're written, so a change that an import holds uncommitted while a run starts is published by a later run, to every sink.
A source keeps only its latest position, so the journal never has more rows than the publication has sources, however long a sink is down, and rows every sink has passed are removed. Normally the journal holds only what the slowest sink hasn't published yet.
Failures and replay
Each build keeps a journal of the outputs it produces, per sink, which is written, a page at a time, before the page
reaches the sink. It holds their identities and the versions of the sources they were published at, not the documents.
Only the journal of a build whose sink completed becomes current: a full build's replaces the current one with one
short write once CompleteAsync succeeds, and an incremental build's replaces the outputs of its sources. A build never
holds a transaction open while it runs, and its completion doesn't copy the catalogue, so a full build of millions of
sources takes as much bookkeeping per page as a small one.
Each sink completes on its own. When one sink of a publication fails, its failure is recorded for it and names it, it stays at its position, and the other sinks complete and move on.
A source whose projection fails, eg because the factory throws for a product whose brand reference is missing, is left out of the build, and the other sources are published to every sink. The run completes with a warning in the Nexus admin that names the sources it left out, each failure is logged with the publication, entity type and ID, and the error is recorded on the assessments the publication produces for the source. What the sinks have of the source depends on the build:
- An incremental build leaves the source as it was: the sinks keep its previous documents, and Vox keeps what it read, so it's published again when that changes or when the source itself does.
- A full build has no documents of the source, so it deletes them as stale, like those of a source that no longer exists. The source is published again when it changes.
The failing source isn't evaluated again at every run, so one bad product doesn't hold back the others or put load on the database. A query field that a model migration is still building is the exception: it defers the whole run, see partial results while capabilities build.
A build that fails or is interrupted isn't resumed:
- A full build starts again from the beginning, as a new build. A full build that stopped without recording its failure, eg because the process did, runs again as a full build too. Repeating the sources it already published is expected.
- An incremental build leaves its work pending for the sink, and the retry evaluates the sources again as they are then. Changes that arrive while a build runs stay pending for the next one. An incremental build that stopped without recording its failure is recorded as failed by the publication's next run, with an error that says it was interrupted, so the sink doesn't keep showing a build that isn't running.
- If the sink completed but Vox couldn't record it, the work is replayed the same way, which the sink repeats safely.
A failed build's journal is kept, since the sink may have made some of its outputs visible, and never becomes current. The next build that publishes a source deletes what the failed build wrote of it and doesn't produce now, and the next full build deletes everything that no journal of a successful build has. Outputs that another source has now aren't deleted. A full build that succeeds then removes the journals it made obsolete, a bounded number of rows at a time.