> ## 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.

# Datastore Helper implementation within MR

> Reference for the Datastore Helper implementation in Atoti Market Risk, covering the AConfigurableSchema store definitions, the DatastoreConfiguratorSetup wiring class, and the available customization consumer classes.

The Datastore Helper 3.4.0-AS6.1 integration in Atoti Market Risk wires store definitions through the DatastoreConfiguratorSetup class. All MR library datastores extend AConfigurableSchema and are applied via DatastoreConfiguratorConsumer beans. For documentation of the library itself, see the [Datastore Helper Documentation](https://docs.activeviam.com/solutions/libraries/datastore-helper/3.4.0-AS6.1/introduction-to-datastore-helper.md).

## Implementations of the AConfigurableSchema class

All the MR libraries datastores are provided as
extensions of the `AConfigurableSchema` and `ATenorAwareSchema` classes. These classes are exposed as individual beans or annotated as `@Configuration`,
then collected and applied to the `IDatastoreConfigurator` object in the `DatastoreConfiguratorSetup` class.

The full list of store definitions is as follows:

| Class | Datastore contents | Exposed as |
| - | - | - |
| `CubeMarketDataStore` | Cube market data. | A bean in the `CubeMarketDataRetrievalConfig` class. |
| `CurveMarketDataStore` | Curve market data. | A bean in the `CurveMarketDataRetrievalConfig` class. |
| `FxRateMarketDataStore` | FX rates. | A bean in the `FxRateMarketDataRetrievalConfig` class. |
| `SpotMarketDataStore` | Spot market data. | A bean in the `SpotMarketDataRetrievalConfig` class. |
| `SurfaceMarketDataStore` | Surface market data. | A bean in the `SurfaceMarketDataRetrievalConfig` class. |
| `BookHierarchyStoreConfig` | A multi-level book hierarchy. | `@Configuration` class wired directly. |
| `BookParentChildStoreConfig` | A parent-child book hierarchy. | `@Configuration` class wired directly. |
| `CounterpartyHierarchyStoreConfig` | A multi-level counterparty hierarchy. | `@Configuration` class wired directly. |
| `CounterpartyParentChildStoreConfig` | A parent-child counterparty hierarchy. | `@Configuration` class wired directly. |
| `CounterpartyStoreConfig` | Counterparty information. | `@Configuration` class wired directly. |
| `CountryStoreConfig` | Country information. | `@Configuration` class wired directly. |
| `LegalEntityHierarchyStoreConfig` | A multi-level legal entity hierarchy. | `@Configuration` class wired directly. |
| `LegalEntityParentChildStoreConfig` | A parent-child legal entity hierarchy. | `@Configuration` class wired directly. |
| `MarketShiftStoreConfig` | Market shifts. | `@Configuration` class wired directly. |
| `RiskFactorsCatalogueStoreConfig` | Risk factors information. | `@Configuration` class wired directly. |
| `ScenariosStoreConfig` | Scenarios per set. | `@Configuration` class wired directly. |
| `TradeAttributesStoreConfig` | Trade attributes. | `@Configuration` class wired directly. |
| `CounterpartyToCountryReferenceConfig` | References between the Counterparty and Country stores. | `@Configuration` class wired directly. |
| `TradeAttributesToBookHierarchyReferenceConfig` | References between the Trade Attributes and Book Hierarchy stores. | `@Configuration` class wired directly. |
| `TradeAttributesToCounterpartyHierarchyReferenceConfig` | References between the Trade Attributes and Counterparty Hierarchy stores. | `@Configuration` class wired directly. |
| `TradeAttributesToCounterpartyReferenceConfig` | References between the Trade Attributes and Counterparty stores. | `@Configuration` class wired directly. |
| `TradeAttributesToLegalEntityHierarchyReferenceConfig` | References between the Trade Attributes and Legal Entity Hierarchy stores. | `@Configuration` class wired directly. |
| `PnLStoreConfig` | Standard PnL store. | `@Configuration` class wired directly. |
| `PnLAggregatedStoreConfig` | Denormalized store for PnL aggregated imports. | `@Configuration` class wired directly. |
| `CorrelationMarketDataStore` | Correlation market data. | A bean in the `CorrelationMarketDataRetrievalConfig` class. |
| `DividendMarketDataStore` | Dividend market data. | A bean in the `DividendMarketDataRetrievalConfig` class. |
| `DynamicTenorsStoreConfig` | Dynamic tenors for rebucketing. | `@Configuration` class wired directly. |
| `SensiLaddersStoreConfig` | Sensitivity ladders. | `@Configuration` class wired directly. |
| `SplitRatioMarketDataStore` | Split ratios for equity instruments. | A bean in the `CorporateActionMarketDataRetrievalConfig` class. |
| `TradeSensitivitiesStoreConfig` | Standard sensitivity data. | `@Configuration` class wired directly. |
| `SensiAggregatedStoreConfig` | Denormalized store for sensitivity aggregated imports. | `@Configuration` class wired directly. |
| `SensiFlatStoreConfig` | Denormalized store for sensitivity store-level imports. | `@Configuration` class wired directly. |
| `TradeSensitivitiesToRiskFactorsCatalogueReferenceConfig` | References between the Trade Sensitivities and Risk Factors Catalogue stores. | `@Configuration` class wired directly. |
| `TradeSensitivitiesToTradeAttributesReferenceConfig` | References between the Trade Sensitivities and Trade Attributes stores. | `@Configuration` class wired directly. |
| `VaRStoreConfig` | Standard VaR data. | `@Configuration` class wired directly. |
| `VaRAggregatedStoreConfig` | Denormalized store for VaR aggregated imports. | `@Configuration` class wired directly. |
| `VaRFlatStoreConfig` | Denormalized store for VaR store-level imports. | `@Configuration` class wired directly. |

Several additional classes are provided to allow groups of stores and references to be imported together:

| Class | Details | Imported classes |
| - | - | - |
| `AllCommonStoresConfig` | Stores used in multiple cubes. | `MarketShiftStoreConfig`. |
| `AllStandardStoresConfig` | Stores used regardless of cube. | `BookHierarchyStoreConfig`, `BookParentChildStoreConfig`, `CounterpartyHierarchyStoreConfig`, `CounterpartyParentChildStoreConfig`, `CounterpartyStoreConfig`, `LegalEntityHierarchyStoreConfig`, `LegalEntityParentChildStoreConfig`, `MarketDataSetStoreConfig`, `RiskFactorsCatalogueStoreConfig`, `ScenariosStoreConfig`, `TradeAttributesStoreConfig`. |
| `AllStandardReferencesConfig` | References used regardless of cube. | `CounterpartyToCountryReferenceConfig`, `TradeAttributesToBookHierarchyReferenceConfig`, `TradeAttributesToCounterpartyReferenceConfig`, `TradeAttributesToCounterpartyHierarchyReferenceConfig`, `TradeAttributesToLegalEntityHierarchyReferenceConfig`. |
| `AllSensiStoresConfig` | Stores used for the sensitivity cube. | `DynamicTenorsStoreConfig`, `SensiLaddersStoreConfig`, `TradeSensitivitiesStoreConfig`. |
| `AllSensiReferencesConfig` | References used for the sensitivity cube. | `TradeSensitivitiesToRiskFactorsCatalogueReferenceConfig`, `TradeSensitivitiesToTradeAttributesReferenceConfig`. |

## The DatastoreConfiguratorSetup class

All Spring beans are collected in the DatastoreConfiguratorSetup class. The`@Configuration` classes are expected to be made
conditional on application properties and thus result in the correct set of datastores for each run mode.

Customizations should be created as `DatastoreConfiguratorConsumer` beans, which are then collected by the class constructor:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
        public DatastoreConfiguratorSetup(
            List<IConfigurableSchema> schemas,
            @Autowired(required = false) List<DatastoreConfiguratorConsumer> customisations) {
        this.schemas = schemas;
        this.customisations = customisations;
    }
```

## What determines the order of customizations?

The customization ordering contract, available from Atoti Market Risk 6.0.10, fixes the sequence in which datastore customization consumers run.

The `DatastoreConfiguratorSetup` class receives every `DatastoreConfiguratorConsumer` bean as an injected `List`. It applies each bean to the `IDatastoreConfigurator` object in list order. Spring sorts that injected list with `AnnotationAwareOrderComparator`. The comparator reads the `org.springframework.core.annotation.Order` annotation declared on the `@Bean` factory method.

### Which class declares the order values?

The order values are named constants of `com.activeviam.mr.common.constants.DatastoreCustomisationSpringBeanOrder`, in the `mr-common-lib` module.

| Constant | Value | Reserved for |
| - | - | - |
| `ACCELERATOR` | 90 | Atoti Market Risk customizations that extend a base store. |
| `PROJECT` | 100 | Project customizations. None of the solution's beans declares this value, and 101 to 104 are free as well. |
| `PROJECT_HOOK` | 105 | The `DatastoreCustomisations.customisations` hook, which a project fills in. |
| `PNL_LEG_ID` | 110 | The customization that appends the `LegId` key field to the `PnL` store. |
| `SIGN_OFF` | 200 | The sign-off customizations. |

Every consumer bean shipped by Atoti Market Risk declares the matching constant rather than a bare number, as in `@Order(DatastoreCustomisationSpringBeanOrder.SIGN_OFF)`. A project customization declares `@Order(DatastoreCustomisationSpringBeanOrder.PROJECT)`, which it shares with nothing.

`PROJECT` is a single value. Several project customizations of one store therefore cannot all declare it. Beans sharing an order value have no guaranteed relative order. The values 101 to 104 are free for that case. The first customization keeps `PROJECT`, and the ones that must follow it declare `@Order(DatastoreCustomisationSpringBeanOrder.PROJECT + 1)` and above.

`PROJECT_HOOK` sits beside the project band rather than on it. A project may fill the hook and also declare a customization of its own. Beans sharing an order value have no guaranteed relative order, so the hook keeps a value of its own.

### Which ordering rules apply?

Three rules follow from the Spring sort applied to the injected bean list:

1. A lower order value runs earlier. A consumer at `PROJECT` (100) runs before a consumer at `SIGN_OFF` (200).
2. A bean with no `@Order` annotation is treated as `Ordered.LOWEST_PRECEDENCE`, which is `Integer.MAX_VALUE`. An unannotated bean therefore runs after every annotated bean, not before.
3. Beans sharing the same order value have no guaranteed relative order. The sort is stable, so the result follows bean registration order. That behavior is not a contract. Two customizations that change the field layout of the same store must be given distinct order values.

The seven consumers at `SIGN_OFF` are safe under the third rule, because each one targets a different store.

### Why does the customization order matter?

The sign-off customization installs up to three key fields on the base store of a cube: `Source` and `Input type` when adjustments are enabled, and `_Version` when sign-off tasks are enabled. Atoti Market Risk enables tasks on the main stores outside DirectQuery and never on the summary cube base stores, so those get `Source` and `Input type` only. It is implemented by `SignOffAnalysisConfig.signOffCustomisations` in the Common Library. The customization works in one of two ways, depending on its `previousField` argument:

* When `previousField` is `null`, the fields are appended at the end of the store.
* When `previousField` names a field, the fields are inserted directly after that anchor field, in that order.

A `DatastoreConfiguratorConsumer` usually does not modify a store when it runs. It registers an intent on the `IDatastoreConfigurator` object instead. The `IDatastoreConfiguratorSetup.datastoreConfigurator` method calls `addModifications` first, then `buildSchemas`. Intents registered against a schema store are applied later, when that schema is built.

The `signOffStores` bean is the exception. It builds the cube-level adjustments store description while it runs, during `addModifications`. That description is complete once `signOffStores` has run, at `SIGN_OFF` (200). A customization ordered after it is never applied to that store.

At build time the Datastore Helper applies the registered intents in a fixed phase order. The phases are field updates, then removals, then insertions, then appends. Consumer order does not change that phase order. Three consequences follow.

**Appended fields are sequenced by consumer order.** Appended fields are collected into a list in consumer order and added at the end of the store. A consumer at `PNL_LEG_ID` (110) appends before a consumer at `SIGN_OFF` (200). The sign-off key fields therefore land after every field appended at a lower order. `LegId`, appended to the `PnL` store at `PNL_LEG_ID`, is one such field.

**Inserted fields are positioned by their anchor, not by consumer order.** The anchor is resolved at build time against the field list. The result is the same whichever order the consumer ran in. The three sign-off beans that insert after the trade status field are `pnlSummarySignOffCustomisations`, `sensiSummarySignOffCustomisations` and `varSummarySignOffCustomisations`. Each of them places its fields identically at any order value.

**For insertions, consumer order decides which customization wins an anchor collision.** Insertions are held in a map keyed by the anchor field name. One store therefore carries only one insertion per anchor. When two customizations insert after the same anchor of the same store, the later consumer wins. The earlier insertion is dropped without an error.

Removals are applied before insertions at build time. Removing a field that another customization uses as its anchor drops that insertion, whatever order either consumer ran in.

### Which stores receive the sign-off key fields?

`SIGN_OFF` (200) is the band reserved for sign-off. Six of its beans are declared by a `signOffCustomisations` factory method. Each of those six adds the sign-off key fields to a base store. The seventh, `signOffStores`, creates the cube-level adjustments store instead of changing a base store.

Sign-off appends the key fields to the main store of each cube. When the summary cube is enabled, sign-off also inserts `Source` and `Input type` into the summary cube's base store, after the trade status field.

| Cube | Main store (appended) | Summary cube base store (inserted) |
| - | - | - |
| PnL | `PnL` | `PnLBaseStore` |
| Sensitivities | `TradeSensitivities` | `SensiBaseStore` |
| VaR | `TradePnLs` | `BaseStore` |

For the order value assigned to each bean, see [Customizations classes](#customizations-classes).

### How to choose an order value for a project customization

* Sign-off appends its key fields to `PnL`, `TradeSensitivities` and `TradePnLs`. A field appended there at `PROJECT` (100) lands before them. A value above 200 places it after them.
* A field appended to `PnLBaseStore`, `SensiBaseStore` or `BaseStore` always follows the sign-off key fields. Sign-off inserts those fields, and insertions are applied before appends. No order value changes that.
* An inserted field is positioned by its anchor field, not by the order value. The order value matters only when another customization inserts after the same anchor of the same store.
* A customization that extends the cube-level adjustments store needs a value below `SIGN_OFF` (200). The `signOffStores` bean builds that store while it runs, so a later customization is dropped without an error.
* The same holds for a store a project consumer creates itself. `addStore` takes a description that is already built, so a customization of that store belongs below the consumer creating it. `PROJECT` (100) for the customization and 101 to 104 for the creating consumer keeps both in the project band.

The following bean appends a field to the `PnL` store at `PROJECT`, before the sign-off key fields:

```java theme={"languages":{"custom":["/engine/python-sdk/6.2/languages/pycon.tmLanguage.json"]}}
@Bean
@Order(DatastoreCustomisationSpringBeanOrder.PROJECT)
public DatastoreConfiguratorConsumer projectCustomisations() {
    return configurator -> configurator.appendField(PNL_STORE_NAME, new CustomField(MY_FIELD, STRING));
}
```

## Customizations classes

Atoti Market Risk contains ten classes that instantiate `DatastoreConfiguratorConsumer` beans. The Order column gives the `DatastoreCustomisationSpringBeanOrder` constant declared by each bean, with its value. For the rules that govern these values, see [What determines the order of customizations?](#what-determines-the-order-of-customizations).

| Class | Bean name | Order | Module | Usage |
| - | - | - | - | - |
| ProductControlDatastoreCustomisations | `productControlCustomisations` | `ACCELERATOR` (90) | `mr-product-control-config` | Operates on the `PnL` store. Makes the `Type` field a key field and adds `Monthly`, `Yearly` and `Lifetime` value fields. |
| DatastoreCustomisations | `customisations` | `PROJECT_HOOK` (105) | `mr-application` | Empty hook intended to provide a place to define simple customizations. |
| LegIdConfiguration | `addLegToPnl` | `PNL_LEG_ID` (110) | `mr-pnl-config` | Appends the `LegId` key field to the `PnL` store. |
| SignOffTaskConfig | `signOffStores` | `SIGN_OFF` (200) | `mr-application` | Creates the cube-level adjustments store. Conditional on the sign-off hierarchy being enabled. |
| PnLSignOffAnalysisConfig | `pnlSignOffCustomisations` | `SIGN_OFF` (200) | `mr-pnl-config` | Appends the sign-off key fields at the end of the `PnL` store. |
| PnLImportSignOffAnalysisConfig | `pnlSummarySignOffCustomisations` | `SIGN_OFF` (200) | `mr-pnl-config` | Inserts the sign-off key fields into the `PnLBaseStore` store, after the trade status field. |
| SensiSignOffAnalysisConfig | `sensiSignOffCustomisations` | `SIGN_OFF` (200) | `mr-sensi-config` | Appends the sign-off key fields at the end of the `TradeSensitivities` store. |
| SensiImportSignOffAnalysisConfig | `sensiSummarySignOffCustomisations` | `SIGN_OFF` (200) | `mr-sensi-config` | Inserts the sign-off key fields into the `SensiBaseStore` store, after the trade status field. |
| VarSignOffAnalysisConfig | `varSignOffCustomisations` | `SIGN_OFF` (200) | `mr-var-config` | Appends the sign-off key fields at the end of the `TradePnLs` store. |
| VarImportSignOffAnalysisConfig | `varSummarySignOffCustomisations` | `SIGN_OFF` (200) | `mr-var-config` | Inserts the sign-off key fields into the `BaseStore` store, after the trade status field. |
