> ## Documentation Index
> Fetch the complete documentation index at: https://docs.activeviam.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Data Versioning

> Java API for data versioning in the Atoti database, for the in-memory datastore and Atoti DirectQuery: epochs, epoch management via `IEpochManagementPolicy` (`KeepLastEpochPolicy`, `KeepAllEpochPolicy`) and `IEpochManager`, querying a specific version, and branch creation, querying, and deletion in the datastore.

> [!NOTE]
>
> For a conceptual overview of data versioning, branches, and epochs, see [How Atoti manages data versioning](https://docs.activeviam.com/concepts/versions/versions.md) on Atoti Hub.

This page documents the Java API for managing data versioning in the Atoti database.
Epochs, epoch management policies and version queries apply to both the in-memory datastore and Atoti DirectQuery.
Branches are available in the datastore only.
For cube versions and the Epoch Dimension, see [Cube versioning](https://docs.activeviam.com/engine/java-sdk/6.2/cube/cube_versioning.md).
For versioning features specific to DirectQuery, such as time travel and refreshes, see [Versioning](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/versioning.md).

## What are epochs?

An epoch is created each time the database gets a new version:

* In the datastore, when a transaction is committed.
* In DirectQuery, when the application is refreshed with `refresh()` or `refresh(ChangeDescription)`.

The following diagram shows epochs created by datastore transactions:

![Epoch Creation](https://mintcdn.com/activeviam/tQvlpZIn_EhELfJK/engine/java-sdk/6.2/assets/core/epoch.png?fit=max\&auto=format\&n=tQvlpZIn_EhELfJK\&q=85\&s=321ad72c92e1e7b0e0f2e6fe2000fb3f)

The Epoch Counter is set to 0 at system startup. A timestamp is recorded for Epoch 0.

The Epoch Counter is incremented whenever a new epoch is created.
The Epoch Counter (otherwise known as Epoch Id) becomes the new version number for the database.
For each new epoch, a new timestamp is also recorded.

For how cube versions relate to database epochs, see [What are versions?](https://docs.activeviam.com/engine/java-sdk/6.2/cube/cube_versioning.md#what-are-versions)

## How does epoch management work?

As long as an epoch is considered valid, all corresponding versions will be kept by their respective multi-versioned
components. This automatically implies a memory cost (and the potential performance cost) of keeping multiple epochs and
their associated versions.

Epochs that are no longer needed can be released, meaning that the corresponding versions may be discarded and garbage
collected. Released epochs are no longer accessible for queries.

### How is the epoch management policy configured?

The epoch manager and its `IEpochManagementPolicy` are defined when building the application:

* In the datastore, call `StartBuilding.application().withEpochPolicy(policy)`.
* In DirectQuery, call `Application.builder(connector).epochPolicy(policy)`.

By default, both the datastore and DirectQuery use the `KeepLastEpochPolicy`.
This policy keeps only the latest epochs, based on their age, their number, or both.
It always keeps the head of every defined branch.

The default configuration of this epoch policy implies that old epochs may only be discarded when a new epoch is created
or when a garbage collection cycle is triggered by the JVM.
This can however be customized further:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
application.withEpochPolicy(
    new KeepLastEpochPolicy().setEpochsToKeep(20).setTimeToKeep(Duration.ofSeconds(5)));
```

will force the application to keep at least the 20 latest epochs and at least 5 seconds of history.

Alternatively, the `KeepAllEpochPolicy` can be used to retain all epochs for the entire lifetime of the application.

### How are available epochs inspected?

Since the Epoch counter is incremented each time a transaction is committed, it may be hard to track which epochs are
available on a running Atoti application.

The epoch manager is responsible for applying the `IEpochManagementPolicy` on the application during its lifespan.
Release of old epochs is performed automatically according to the policy, or can be performed manually through the
Epoch Manager MBean (releasing epochs, dropping branches, listing existing branches).
The same operations are available programmatically via the `IEpochManager` interface.

The `IDatabase` and `IVersionHistory` interfaces provide methods to access the versions that are not released.

The `getEpochsUsage` operation, available in the Epoch Manager MBean, provides statistics about the versions held by
each multi-versioned component of the application as well as the released and discarded epochs.

### How is a specific version queried?

Each `IDatabaseVersion` provides a `getQueryRunner()` method to execute queries on that version of the data.

Queries performed on this `IQueryRunner` interface will return data corresponding to facts as-of the corresponding
epoch.

The [Epoch Dimension](https://docs.activeviam.com/engine/java-sdk/6.2/cube/cube_versioning.md#what-is-the-epoch-dimension) is available when performing **MDX Queries** and allows for complex cross-epoch
calculations.

## What are branches?

> [!NOTE]
>
> For a conceptual overview of branches and What-If analysis, see [How Atoti manages data versioning](https://docs.activeviam.com/concepts/versions/versions.md) on Atoti Hub.

Branches are available in the in-memory datastore only.
DirectQuery databases do not support branches: they work on the `master` branch only.
For more information, see [Branching](https://docs.activeviam.com/engine/java-sdk/6.2/directquery/versioning.md#branching).

In practice every transaction is made on some branch, which is assumed to be "master" if unspecified.
A branch can therefore be represented by the set of the transactions done on it.

### How do branches work in Atoti?

Atoti uses a Version History to link all the versions of the components using MVCC together.
This `IVersionHistory` is **always linear**, even with multiple branches.

Branch information is held in the `IHistoryNode`s of the `IVersionHistory`, which is created temporally,
commit after commit:

![Branches\_1](https://mintcdn.com/activeviam/fu1io3zqrxuzLJNd/engine/java-sdk/6.2/assets/core/branch_1.png?fit=max\&auto=format\&n=fu1io3zqrxuzLJNd\&q=85\&s=71cd3ec8ad66aaffa06332387de1ba94)

It is possible to define, use and navigate through branches with Atoti:

* Initially, there is only one branch, called `master`.

* When feeding data into a datastore, each transaction can be applied from any existing branch and committed on any
  other branch, creating a new one if needed.

* Once created, it is possible to continue committing data on a branch and update its head
  (the latest version of a branch).

There are however operations that are limited or not possible with branches in Atoti:

* When performing a transaction, only the mentioned branch will be updated. If some data must be committed on multiple
  branches, a transaction must be performed on each of the impacted branches.

* It is **not** possible to merge or rebase branches in Atoti. However, a branch can be fast-forwarded to another
  branch's head using `IDatabaseService.fastForward()`.

### How is a branch created?

To create a branch, start a transaction with `startTransactionOnBranch` or `startTransactionFromBranch` on the `ITransactionManager`.
The branch is created when the transaction is committed.

### How is data queried on a branch?

It is possible to perform a query on any version of any branch as long as the specified Epoch is still valid.
The query's results will correspond to the data as it was at the specified epoch within its corresponding branch.
For more information about the epoch policy, see the [How is the epoch management policy configured?](#how-is-the-epoch-management-policy-configured) section.

* The [Database REST API](https://docs.activeviam.com/engine/java-sdk/6.2/rest-api/database_rest_api.md) supports branch-specific queries on the
  Database. The query returns data corresponding to the HEAD of the requested branch.

* The [Epoch Dimension](https://docs.activeviam.com/engine/java-sdk/6.2/cube/cube_versioning.md#what-is-the-epoch-dimension)'s Branch/What-if level enables analysis of aggregated data across scenarios
  by changing the member of the Epoch Dimension queried by the MDX code.

### How are branches listed and deleted?

In order to keep track of the existing branches on an Atoti application, the following method
`IEpochManager.getBranches()` is available and returns the names of the current valid branches. The application also
exposes an MBean named `showBranches` that will print various information about branches such as the first epoch of a
branch, the latest epoch of a branch and the epoch on which a branch was created.

When a branch is no longer necessary, it can be dropped to free the memory held by the versions corresponding to its
underlying epochs and their associated versions.

It is possible to delete a branch by calling `IEpochManager.releaseBranch(String branchName)`, which is available as an
MBean named `dropBranch`.
Note that a branch can only be dropped if it does not contain the latest version. If the branch contains the latest
version, it will be dropped after the next commit.
Similarly, a branch will be effectively dropped if none of the related versions are being used.

### What are the performance characteristics of branches?

Thanks to the linear design of branches in Atoti, using branches does not imply an additional memory usage cost.
Moreover, there is no inherent cost incurred by the used branches count increase.

However, the current design leads to the following caveat:

> Performing a commit on a branch B will have a time cost equal to the cost of this commit in a branch-less scenario
> PLUS the cost of reverting the state of the store from its current head to the head of the branch B.
> Unfortunately, this additional cost is uncorrelated to the commit itself, but depends not only on the operations
> that occur on the datastore, but also on the order on which they occurred.

It is also worth mentioning that Indexed aggregate providers are multi-versioned components as well and therefore
support branches. As a consequence, they contribute to the memory consumption of each branch by holding pre-aggregated
data. Note that it is not the case for the Just-In-Time aggregates provider, as aggregates are computed on the fly.
