# Historian

> How the eaxScada historian stores and queries time series, with the columnar historian engine in every edition and the Hive-partitioned CSV engine in builds without the embedded database.

Product: eaxScada · Type: Explanation · Editions: Starter, Pro, Enterprise
Source: https://eaxware.com/docs/eaxscada/explanation/historian/
Status: migrated page, not yet verified against the current code.

Process optimisation, regulatory compliance and incident investigation need high-throughput time-series logging. This page explains **eaxScada's two historian engines**: the columnar historian engine (the embedded database), which stores history in **every edition**, Starter included, and the pure-Go Hive-partitioned CSV appender, which runs only in builds without the embedded database (the command-line tools). It also covers deadband filtering, downsampling, the nightly snapshot and, in Pro and Enterprise, the daily Parquet export, and how to restore the history from either. Which engine runs is decided by the build, not by the licence.

The alarm subsystem that shares this storage is described in [Alarms](/docs/eaxscada/explanation/alarms/).
[Image: The historian trend view: two hours of four tags of the documentation plant (reactor temperature and three tank levels), with the sample table below.]
[Image: The historian trend view: two hours of four tags of the documentation plant (reactor temperature and three tank levels), with the sample table below.]

The historian trend view: four tags over two hours, read back from the Hive-partitioned history.
---

## 1. Architecture

The diagram follows a point through the columnar engine, the one that stores history in every edition. Section 2 describes both engines.

**Diagram: From a tag change to the columnar store** (data flow)

A changed tag value passes its logging rule, waits in the ingest queue and is written in batches to the columnar store. An overflow, a spool on disk and a memory cache cover the cases where the queue is full or the store refuses a batch.

**Parts**

- **Tag engine** (service or process): a value changes
- **Logging rule** (service or process): on change, deadband, period
- **Ingest queue** (service or process): 100,000 points
- **Batch worker** (service or process): 5,000 points or 2 s
- **Overflow** (service or process): 1,000,000 points, kept in order
- **Columnar store** (data store, every edition): scada_history.duckdb appended in batches
- **History reads** (service or process): trends, exports, reports, AI history tools
- **Memory cache** (service or process): points not yet in the store
- **System alarm** (service or process): ALM-SYS-HISTORIAN-LOST points counted as lost. Also raised when the queue and the overflow are both full.
- **Spool on disk** (data store): up to 2 GB, in order

**Connections**

- **Tag engine → Logging rule** (data or telemetry)
- **Logging rule → Ingest queue** (data or telemetry)
- **Ingest queue → Batch worker** (data or telemetry)
- **Batch worker → Columnar store** (data or telemetry)
- **Ingest queue → Overflow** (data or telemetry): queue full
- **Overflow → Ingest queue** (data or telemetry): in order. The batch worker takes the overflow after the queue, in write order.
- **Columnar store → Spool on disk** (data or telemetry): store refuses. The batch worker writes a batch the store refuses to the spool.
- **Spool on disk → Columnar store** (data or telemetry): every minute. The spool is retried every minute and survives a restart.
- **Columnar store → History reads** (data or telemetry): queries
- **Memory cache → History reads** (data or telemetry): recent trends
- **Spool on disk → System alarm** (alarm or event): spool full

The normal path runs along the top. Nothing is dropped silently: points that cannot be kept are counted and raise the system alarm.

---

## 2. The two storage engines

Historians often lock users into proprietary databases, closed file formats or per-tag licence fees. eaxScada uses open formats in every edition.

### 2.1 The Hive-partitioned CSV files

The CSV engine is the store of builds without the embedded database (the command-line tools), unchanged. **The release server writes no CSV partitions**: in every edition of the release build, Free included, the columnar store is the history's single store. The rule is per build, not per licence. Earlier releases wrote every point twice, to the columnar store and to these folders as a CSV copy; that copy is no longer written. CSV history written before the upgrade is still read (section 2.3).

- **Pure Go, no CGO.** Builds on any platform with no C library dependencies (`internal/historian/hive_appender.go`).
- **Partitioned by date and tag:**
  ```
  data/historian/
    └── year=YYYY/
        └── month=MM/
            └── day=DD/
                └── tag={SanitizedTagPath}/
                    ├── data.csv
                    └── late.csv   (only when late samples arrived)
  ```
  `data.csv` holds the day's rows in time order. A sample older than the newest row already in `data.csv` (a late, backfilled sample) goes to `late.csv` in the same folder; see [Late samples and repeated timestamps](#25b-late-samples-and-repeated-timestamps).
- **CSV schema.** RFC-4180 CSV with the header `timestamp_ns,value,quality,eng_units`.
- **Buffered streaming.** Flushes every 2,000 ms or every 5,000 points.
- **Plain files.** In a build without the embedded database, the files open directly in a spreadsheet, a Python script or any data-lake tool. On the release server they are no longer a live copy of the history: for files other tools can read, use the scheduled export (`historian.export`, one Hive-partitioned Parquet file per closed day, Pro and Enterprise; section 4.3).

### 2.2 The columnar historian engine, in every edition

- **Included** in every edition, Starter included: the release server is built with it (build tags `pro || enterprise`, which compile in every capability; the licence decides the edition). The store is the file `scada_history.duckdb` in the historian folder.
- **The features built on it are Pro and Enterprise:** part and lot genealogy and the Parquet analytics export (section 4).
- **Vectorised ingestion** through an in-process appender.
- **SQL downsampling.** min, max, avg, first, last and count over millions of rows, for fast trends.
- **Parquet compression.** Typically 10x–50x smaller than raw CSV, with ZSTD compression.
- **Encryption at rest (Enterprise).** AES-GCM-256 transparent data encryption of the historian files. The key comes from an environment variable named in the configuration.

#### Engine version and file format

eaxScada embeds **DuckDB 2.0.1**. Every database file the server creates (the historian, the audit trail, security, alarms, recipes, genealogy, the log console, the shift log index, the collaboration archive, the nightly snapshot) is still written in the **v1.0.0 storage format** (header 64; 68 when encrypted). Existing files are opened where they are and never converted, so the previous packages (DuckDB 2.0.0, and 1.5.6 before it) still open every file, snapshot and audit copy a 2.0.1 server wrote. The server also opens a file in the DuckDB 2.0 format.

**A file in a newer format than 2.0's is refused, untouched.** eaxScada reads only the file's first bytes, never opens, renames or writes it, and says why: "the database file ... is in the DuckDB newer format (...), written by a newer eaxScada; this eaxScada (DuckDB v2.0.1, reads up to the 2.0 format (999)) cannot open it and leaves the file as it is". A file that is not a database file at all (empty, cut short, another kind of file) is refused the same way. **What to do:** start the newer eaxScada again, or restore the backup taken before the upgrade. Do not delete the file. The start log ("DuckDB engine", one "DuckDB store" line per store) and System Health's [Database stores](/docs/eaxscada/reference/metrics/#database-stores) show the engine, the newest format it opens and each store's format and state. The security store refused stops the server's start; a refused historian store keeps its points in the spool.

#### When a write leaves the database unusable

When a commit fails, or the database reports itself invalidated (a full disk, a write-ahead log write error, an I/O error, out of memory), the historian, alarms, recipes, log console, collaboration archive and shift log index stores **close their file and open it again** instead of retrying on the dead instance until a restart:

- writes to the store are held while it reopens; nothing is acknowledged that is not committed;
- the file is opened again only once no connection of the old instance is open;
- a reopen that fails is tried again with a growing delay (1 s, doubling to 1 min), and the store is shown **down** in the meantime;
- the historian's points wait in the [spool](#25e-when-the-store-does-not-take-writes-the-spool) and are written in order once the store is open.

The security store does the same (17 November), and reloads users, roles and rules from the file after the reopen; while it reopens or is down every permission check and every sign-in is refused: [When the security store reopens after a failed write](/docs/platform/explanation/security-and-part-11/#when-the-security-store-reopens-after-a-failed-write).

No sync, write-ahead log or checkpoint setting is changed by this. The audit trail keeps its own close and reopen after a failed write ([When the trail is down](/docs/platform/explanation/security-and-part-11/#when-the-trail-is-down)); genealogy keeps failing closed until the server restarts.

#### Encryption at rest on offline and air-gapped installs

Writing an encrypted historian needs one storage extension next to the columnar engine. The release package ships it, and eaxScada loads it only from the package. The server never downloads an extension at run time and never uses a per-user extension cache, so a plant PC with no internet access works the same as a connected one.

- **Location.** The extension is in the `historian_ext` folder next to the server executable: `bin\historian_ext\v2.0.1\windows_amd64\` in the Windows package, and `/app/historian_ext/v2.0.1/linux_amd64/` in the Linux container image (the `v2.0.0` and `v1.5.6` folders of earlier releases are no longer used). `install.ps1` copies it into the install folder's `bin\`, and it refuses to install from a package that is missing it.
- **Integrity.** The release build fetches the file from the storage engine's official extension repository. It checks the size and the SHA-256 against the values pinned in the source, and it checks them again in the package. At start-up the server checks the file once more, and the engine checks the file's signature when it loads it.
- **Other locations.** Set `historian.extension_dir` in the server configuration, or the environment variable `EAX_HISTORIAN_EXT_DIR`, to a folder with the same layout (`<folder>/v2.0.1/<platform>/`). The environment variable takes precedence over the configuration key. The version folder follows the embedded DuckDB version: when an upgrade moves to a new DuckDB version, put the matching bundle in your folder before you start the new release.
- **If the extension is missing.** When encryption is enabled and the file is missing or different, the historian refuses to start. Nothing is written unencrypted. The log names the exact path where the server expected the file. Reinstall the package, or copy the `historian_ext` folder from it.
- **Unencrypted historian.** It needs no extension and works without the folder.

### 2.3 Upgrading, and history written as CSV

Moving from Starter to Pro or Enterprise changes the licence only: the history stays in the same columnar store, with **no migration and no downtime**.

**CSV history from before the upgrade is still read.** The release server writes no CSV partitions any more, but the CSV history already on disk (written by a build without the embedded database, by an install upgraded from one, or before a store reset) is read up to each tag's first point in the columnar store, by the rule below. Trends and the history API merge it with the columnar store. The CSV files stay where they are, and are read, until you import them into the columnar store: [Import the CSV history into the store](/docs/eaxscada/how-to/import-csv-history-into-the-store/). An administrator does it from **System Health > Historian storage > Review import…** while the server runs, signed with the password and a reason (desktop and tablet), or offline with `eaxscada historian-migrate-csv`, with the server stopped. Either way, each day is verified in the store before its CSV files are deleted. A day the import keeps for attention stays CSV and is read by the same rule, until **Retry kept days** (or a new run of the command) imports it. The columnar engine can also query those folders in place, for example:

```sql
SELECT
  date_trunc('minute', to_timestamp(timestamp_ns / 1000000000)) AS bucket,
  avg(value) AS avg_temp,
  max(value) AS max_temp
FROM 'data/historian/year=*/*/*/*/*.csv'
WHERE tag_path = 'Plant/Line1/Reactor1/Temperature'
GROUP BY 1 ORDER BY 1 ASC;
```

#### Where a tag's CSV history ends

On an install upgraded from a build without the columnar store, a tag's history starts in the CSV partitions and goes on in the columnar store. Every reader (trends, `/api/history`, the AI assistant's history tool, the historian export, the scheduled export, report and analytics datasets, and the offline historian backup) uses one rule:

- **The CSV history of a tag ends where the columnar store began receiving that tag** (its first row in write order), not at the store's earliest timestamp.
- **Before that point, the CSV history is read**, and the columnar store's value is taken wherever it has the same tag and timestamp.
- **A backfill no longer hides older CSV history.** A driver or an edge device forwarding its buffer can write a sample with a timestamp from the CSV era. Earlier releases then showed nothing between that sample and the start of the columnar store, in trends, exports and report datasets. That CSV history now shows, with the backfilled value at its own timestamp.
- **With a point limit**, the newest points of the whole merged series are returned.
- CSV history written by earlier releases after the columnar store's start that the store lacks (batches the store refused then, held only by the old CSV copy) is not shown while it stays CSV. The [CSV history import](/docs/eaxscada/how-to/import-csv-history-into-the-store/) brings these points into the store, counted as "recovered", and they show from then on.

**Diagram: Where one tag's CSV history ends** (timeline)

On one tag's time axis, the CSV history is read up to the tag's first row in the columnar store, counted in write order; from there on only the store is read. A sample written later with an older timestamp is shown at its own time and does not move that point. Where both hold the same tag and timestamp, the store's value is shown. CSV points after the bound are shown only once an approved CSV import has added them to the store.

Time runs left to right: CSV history, then columnar store. The lengths are not to scale.

**What a trend, export or report reads**

- **CSV partitions**: read strictly before the bound (read). CSV points from the bound on are not read.
- **Columnar store**: every write since the bound (read; bound)

**Special cases**

- **Late sample**: written later, older time (shown at its own time). A backfill reaches the store after the bound was set; it does not move the bound, and the CSV around it is still read.
- **Same tag and time**: held in both (store value shown)
- **CSV point after the bound**: not in the store (not shown). It is shown once the CSV import has added it to the store.
- **CSV import**: only after an approval (adds only what the store lacks). An administrator approves the import in the Studio, or runs the offline command. It is never started by an upgrade or a restart.

**Connections**

- **CSV import → CSV point after the bound** (data or telemetry). The import adds the CSV point to the store; from then on it is read from the store.

The bound is the first row the store received for the tag, not its earliest timestamp, so a late sample never hides CSV history.

#### Two tag paths in one CSV folder

A CSV folder name cannot hold every character of a tag path, so two paths that differ only in such characters (for example `Fix/A/B` and `Fix/A_B`) share one folder. Earlier releases saw only the path of the folder's first row there: the other path's points were left out of the historian export and the offline historian backup, and a shorter retention of the first path deleted the folder, the other path's rows with it. Now the paths of a folder come from its rows:

- **Both paths are exported and backed up.**
- **A shared folder is kept until the longest retention** of the store, never deleted by one path's shorter retention.

#### How trends read CSV history

- **With the columnar engine** (the release server), the CSV history of a tag (from before the columnar store's first point of that tag, or every point on an install that stores CSV only) is read with DuckDB's own CSV reader. The files of the requested days and tags are named directly, and all the tags of one request are read in **one query**, with the tag and time filters applied while the files are scanned.
- **The built-in reader** (builds without the embedded database, and the fallback below) names the days of the requested window too: it no longer lists every day folder of the store for each tag. On a 30-day, 200-tag store, a 10-tag read of the last 10 minutes went from 0.57 s to 0.02 s on a workstation, and from 0.17 s to 0.02 s on a dual-core thin client.
- **Both return the same points:** one point per tag and timestamp, the later write (a backfill in `late.csv` wins over `data.csv`), and the quality and simulated mark as written; older files without the simulated column read as before.
- **On any doubt the built-in reader answers for that tag:** a file still being written (a last line without its newline, or a file that grew during the read), a malformed row, two different rows with one timestamp in one file, or an error of the CSV reader (logged once).
- **Tag paths written quoted read back.** A tag path with a comma, double quotes (an OPC UA path such as `"DB1"."Speed"`) or a leading space is written quoted in the CSV cell. Earlier releases returned no history for such a tag; it now shows in trends.
- **Only `data.csv` and `late.csv`** are read in a tag's day folder. Other `*.csv` files placed there are ignored (nothing in eaxScada writes them).
- **Reads do not wait for a CSV write in progress.** A read of the CSV partitions used to wait once per tag for the writer (10 tags over 24 hours: about 10 s); it no longer does, and the results are the same.

### 2.4 Table schema (`tag_history`)

```sql
CREATE TABLE IF NOT EXISTS tag_history (
    timestamp BIGINT,         -- Unix nanoseconds
    tag_path VARCHAR,         -- Full ISA-95 UNS path
    value DOUBLE,             -- Process measurement (IEEE 754 Float64)
    quality USMALLINT,        -- OPC quality code (Good, Uncertain or Bad by its major bits, see 5.2)
    year INTEGER,             -- Partitioning column
    month INTEGER,            -- Partitioning column
    day INTEGER               -- Partitioning column
);

CREATE INDEX IF NOT EXISTS idx_tag_history_path_time
ON tag_history (tag_path, timestamp);
```

### 2.5 Ingestion and micro-batching

Committing each point in its own transaction would bottleneck on I/O, so data flows through an asynchronous buffering worker (`internal/historian/`):

1. When a tag changes, `histEng.ProcessPoint(path, val, quality, ts)` submits a `DataPoint` to a buffered Go channel:
   ```go
   appenderCh = make(chan DataPoint, 100000)
   ```
2. A background `ingestionWorker()` goroutine drains the channel into a batch.
3. A batch is flushed when **either** condition is met:
   - it reaches **5,000 points**, or
   - the flush ticker fires (every **2,000 ms**).
4. In every edition, batches go through the columnar engine's vectorised appender, and nowhere else (no CSV copy). A batch the store does not take waits in the spool on disk (section 2.5e). In builds without the embedded database, they are appended to the partitioned CSV files (`data.csv`, or `late.csv` for late samples).

### 2.5a When the historian falls behind

The ingest queue holds 100,000 points. When the store writes more slowly than points arrive (a slow disk, a burst of changes after a network outage), the queue fills up. Earlier releases then kept the extra points in memory only: they showed on recent trends but never reached the database or the CSV partitions, and were gone after a restart. Now:

- **Points that arrive while the queue is full are stored.** They wait in an overflow behind the queue, up to 1,000,000 points, and are written in the order they arrived.
- **Drivers never wait on the database.** Only when the overflow is full too does one caller wait, for at most 100 ms, for room. After that, points are counted as lost until the store catches up.
- **Stopping the server writes everything still queued** before the store closes.
- **One CSV partition that cannot be written does not stop the others** (builds without the embedded database). The other partitions of the batch are written, and the failed points are counted as lost.
- **Lost points are counted, never dropped silently.** With the columnar store, a point the store refuses is not lost: it waits in the spool (section 2.5e). A point is lost when the spool is full or cannot take it, when it is quarantined or in a damaged spool record (section 2.5e), when a CSV partition cannot be written (builds without the embedded database), or when the queue and the overflow are both full. A lost point stays on recent trends from memory only, and is gone after a restart. The server log reports lost points at most once every 10 s, with the count. "Points written" counts only points actually stored.

**Where to see it.**

| Where | What it shows |
|---|---|
| **System Health**, historian | `lost` (points lost since start), `last_loss` (when) and `last_loss_reason` (why) |
| `/metrics` | `eaxscada_historian_lost_points_total`; `eaxscada_historian_ingest_dropped_total` counts the points that found the queue full and went to the overflow (they are stored) |
| System alarm **ALM-SYS-HISTORIAN-LOST** (High) | "Historian could not store some points" |

**ALM-SYS-HISTORIAN-LOST** is active while a point was lost within the last hour, and clears by itself one hour after the last lost point, like the purge alarm. It means a gap in the stored history: the trend you see now may show values that will be missing after a restart, and reports and exports will not have them. What to do:

1. Open **System Health** and read `last_loss_reason`. The server log has the store's own error at the same time.
2. If the spool was full or the store refused the points: check the free disk space and the historian folder's access (the database file, the `spool` folder, or the CSV partition named in the log). See [Keep the historian within its disk budget](/docs/eaxscada/how-to/keep-historian-within-disk-budget/).
3. If the queue and the overflow were full: the store cannot keep up with the logging rate. Raise deadbands or minimum intervals on fast tags (section 3), or move the historian to a faster disk.
4. Record the period in your shift log or deviation record when the history matters for quality: the points lost in it cannot be recovered.

### 2.5b Late samples and repeated timestamps

- **A timestamp written twice: the later write wins.** When one tag gets two values with exactly the same timestamp (a driver or edge device sending a sample again, a correction), every reader returns that timestamp **once**, with the value written **last**: the in-memory cache, the CSV and columnar stores, trends, the history API and exports agree. The earlier value is not shown next to it.
- **Late (backfilled) samples are visible.** A sample that arrives after newer ones were stored, for example a driver or an edge device forwarding values it buffered during a network outage, is kept and shown in trends, history queries and exports at its own timestamp, like any other sample.
- **`late.csv` next to `data.csv`.** In the CSV store, such a sample is written to `late.csv` in the same partition folder, so `data.csv` stays in time order. Readers read both files, so you never need to merge them yourself; a script reading the folder directly should read `data.csv` first, then `late.csv`. eaxScada reads no other `*.csv` file in the folder.
- **Retention.** A purge removes the late samples of the purged days with the rest of the day, also from the in-memory cache.

### 2.5c The in-memory cache of recent points

Besides the store, the historian keeps a cache in the server's memory for the points that are **not** on disk. Earlier releases kept every point there, up to 50,000 per tag, whether or not it was already on disk: under a steady load (1,000 tags changing every second) the server's memory grew by about 500 MB per hour and never levelled off. A later release kept the newest 600 stored points (or 10 minutes) of each tag. Now:

- **With the columnar engine (the release server), a stored point leaves memory at once.** Trends, exports, reports and the AI assistant's history tools read it from the columnar store. Under normal operation the cache is empty.
- **Builds without the embedded database (CSV store only)** keep a stored point in memory while it is among the tag's **600 newest stored points** and **less than 10 minutes old**, because each of their reads costs a day file. Older ones are read from the CSV partitions.
- **Points no store took stay.** A point that is not in the store (logging paused by the disk guard, a point waiting in the spool, part of a CSV batch that was refused) stays in the cache as before, up to 50,000 per tag, so recent trends still show it.
- **The later write still wins.** A stored point is kept while an unstored point has the same tag and timestamp, so the rule of section 2.5b holds.
- **Reads do not wait for writes.** Each read used to wait for the cache's lock, which every store write held for its whole duration (on a small PC at 1,000 tags per second, up to seconds per write). With the cache empty a read now takes no lock; with points no store took, it merges them as before.
- **When a columnar query fails**, the history is unavailable: `/api/history` answers `503` and trends say "History unavailable" (section 2.5d). No CSV copy is written any more, so there is no fallback that could answer with every point, and a partial series is never returned.

What operators see does not change: one point per tag and timestamp, the later write, and the values, quality and simulated mark as written, in trends, exports, reports and the AI assistant's history tools. What changes is memory and speed. Measured on a workstation at 1,000 tag changes per second, 10 tags over the last 10 minutes, each viewer reading once a second:

| Viewers | Before (p50 / p95) | Now (p50 / p95) |
|---|---|---|
| 1 | 1.87 s / 2.00 s | 0.13 s / 0.17 s |
| 10 | 2.03 s / 3.92 s | 0.11 s / 0.13 s |
| 50 | 4.87 s / 8.00 s | 0.20 s / 0.26 s |

No point was lost. The server's resident memory at 1,000 tag changes per second went from about 1,075 MB to about 445 MB on the same workstation, most of the saving from the smaller NATS replay buffer of the same release (at most 64 MB instead of 256 MB, each change on it once: [`nats.telemetry_buffer`](/docs/eaxscada/reference/server-configuration/)), the rest from this cache.

**Exports include every day.** A CSV or JSON export of a store without the CSV copy (with encryption at rest, and now every columnar store) listed its days from the memory cache and the CSV files only, so the days whose points were no longer in memory (yesterday and before) were left out. It now lists the columnar store's days and tags too; an error reading them fails the export instead of exporting less.

### 2.5d When the history store does not answer

A read of the columnar store waits 3 s, then tries once more with 10 s. When it still gets no answer (or an error), the history is unavailable. Earlier releases answered from the CSV copy when it was written, and otherwise (with encryption at rest) with the recent points from memory only: a trend, a report or the AI assistant saw a shorter history with nothing to say so. No CSV copy is written any more (section 2.1), so this holds for every columnar store, with or without encryption. An unavailable history is said so, and never shown as a shorter one:

- **`/api/history` answers `503`** with `{"status": "history_unavailable"}`.
- **The AI assistant's history tool** (`scada_query_tag_history`) returns an error, and the assistant reports it.
- **Trends say "History unavailable".** The trend widget of screens, dashboard trends, gauge sparklines and the Studio's historian trend keep drawing their live samples, and a notice over the plotted area says that only the samples since the time given are drawn, not the history before them. **Retry** reads again at once, and they retry by themselves every 30 s. The notice goes once a read succeeds, and the history then fills in.
- **The History page** (`/history`) draws nothing rather than part of the history, and says so above the chart. The Studio's values table shows no rows rather than an older read.
- **System Health's history charts** show no series and say why.
- **Exports and backups fail instead of writing less:** the historian export (`/api/historian/export`, CSV and JSON) and the scheduled export (Parquet by default, or CSV) fail the day, and the offline historian backup (`eaxscada historian-backup`) fails.
[Image: A runtime screen with a trend of three tank levels: a "History unavailable" notice over the chart says that only the live samples since 18:58:48 are drawn, with a Retry button and "Retries every 30 s".]
[Image: A runtime screen with a trend of three tank levels: a "History unavailable" notice over the chart says that only the live samples since 18:58:48 are drawn, with a Retry button and "Retries every 30 s".]

A runtime trend while the history store does not answer: the live samples go on, the missing history is named, and the trend retries every 30 s. The runtime is dark by design; the Studio's notice follows its light or dark theme.
### 2.5e When the store does not take writes: the spool

When the columnar store refuses a write, or does not open at start, new points are not lost. They wait in the historian **spool**, a folder on disk (`<historian folder>/spool/`), in the order they arrived, and are written to the store as soon as it takes writes again. Earlier releases counted such points lost and kept them in memory only, gone after a restart.

- **In order.** While the spool holds points, every new batch goes behind them, even when the store would take it: no later write overtakes an earlier one, and the later write of a tag and timestamp still wins (section 2.5b).
- **Retried every minute while the store is down.** The spool is written to the store in order; after a failure the next try is a minute later, or 2 s later while the store is isolating a point (below). The spool survives a restart.
- **None is lost while the spool has room.** `historian.spool.max_size` (default 2 GB) is its limit. When the spool is full, new points that do not fit are counted lost (`ALM-SYS-HISTORIAN-LOST`, "the spool is full"); what the spool holds is kept.
- **Recent trends show the waiting points** from memory meanwhile. History reads that need the store say "History unavailable" while it does not answer (section 2.5d).
- **A store that does not open at start** (without encryption at rest: a locked or damaged file, its disk gone): the server starts, keeps the points in the spool, and opens the store as soon as it can, tried every minute, without a restart. An encrypted store that does not open still stops the server, as before.
- **Under encryption at rest the spool is encrypted too**, with a key derived from the store's key: no tag path or value is on disk in the clear.

#### The store's state: ok, isolating or down

When the store refuses a batch, the points go to the spool first, and the historian then makes a small test write to the store (the probe, into a table of its own). The answer tells an outage from a single point the store refuses. The store is in one of three states:

| State | When | System alarm |
|---|---|---|
| **ok** | The store takes writes. | none |
| **isolating** | The store refused a batch but takes the probe write, and has written a data point in the last 30 s. | `ALM-SYS-HISTORIAN-ISOLATING` (Medium) |
| **down** | The store did not open, refuses the probe too, the spool or its quarantine could not be written, the store refuses every point (below), no data point has been written for 30 s after a refusal, or one write to the store has not returned after 30 s, with or without a refusal before it. The 30 s also cover a probe that hangs. | `ALM-SYS-HISTORIAN-STORE-DOWN` (High) |

One state drives both alarms, so `ALM-SYS-HISTORIAN-ISOLATING` and `ALM-SYS-HISTORIAN-STORE-DOWN` are never active together. A store that stops taking writes while a point is being isolated is reported down, never as isolating.

- **Every refusal is probed,** the first live batch included. Before, the first refusal of a live batch marked the store down at once, with no probe.
- **While the store takes the probe, the refused batch is tried again every 2 s,** not every minute. After 5 refusals in a row it is written one point at a time to find the point the store refuses, and the other points are written in order. The search now starts within seconds; before, it started about 5 minutes after the first refusal.
- **While the store is down,** the spool is tried every minute, as before.
- **A write that hangs is down after 30 s** (19 November). Each write to the store is timed while it is in flight: once it has not returned after 30 s, the store reads down (`down_reason` `stalled`) and `ALM-SYS-HISTORIAN-STORE-DOWN` is raised at the next check of the system's resources (every 10 s), even when the store refused nothing before. The state is read from the clock, so the status answers while the write is still blocked. When the write returns, the state is worked out again: `ok` if it went through, otherwise the refusal is handled as above. Before, a write that hung before any refusal left the state `ok` for as long as it hung.

#### A point the store refuses for good: confirmed, then quarantined

A point the store refuses on its own is quarantined only after the store has written a later point of the same batch. That later point proves the store takes data points now; the probe's own table is no such proof.

- **Up to 3 refused points in a row** wait for that proof, in the spool.
- **A 4th refused point in a row** means the store refuses every point: it is reported down (`down_reason` `refuses_every_point`), and nothing is quarantined. The points stay in the spool, in order, until the store takes them.
- Before, a store that took the probe but no data point lost one good point to the quarantine at each round of the search.

**The search halves the batch.** The historian finds the refused point by halving the batch, not one point at a time. A point 1,200 deep in a batch of 2,000 is found in about 12 writes instead of about 1,200, so `ALM-SYS-HISTORIAN-ISOLATING` clears within one 2 s tick instead of a minute or more. The same points are written in the same order, and the same points are quarantined. A refused half is one transaction, so none of its points reach the store and none is written twice. Once the refused batch is past, the store state is `ok` at once; before, it stayed isolating until the next store write, and read down after 30 s if no new point came.

A quarantined point is kept in a quarantine file in the spool folder (`quarantine-<seq>.wal`, never deleted) and counted lost once (`ALM-SYS-HISTORIAN-LOST`); the other points are written in order. The store's error for it is kept beside it in `quarantine-<seq>.err` (sealed like the spool under encryption at rest), so the cause is still known after a restart.

#### The store's state in the status

`GET /api/historian/storage` (in `spool`) and System Health's status (in `resources.historian.spool`) carry:

| Field | Meaning |
|---|---|
| `store_state` | `ok`, `isolating` or `down` |
| `store_down` | `true` only when `store_state` is `down` (not while isolating) |
| `down_reason` | When down: `open_failed` (the store did not open), `refused` (it refused a write and the probe), `spool_write` (the spool or its quarantine could not be written), `stalled` (no data point written for 30 s after a refusal, or one write in flight for 30 s; `store_down_since` is then the earlier of the two times plus 30 s), `refuses_every_point` (a 4th refused point in a row) |
| `isolating_since` | The first refusal of this episode |
| `isolation` | While a point is looked for: `first_seq` and `last_seq` (the batch's spool numbers), `at_seq` (the last seq settled), `search_to` (the last seq of the part known to hold the refused point), `checked` and `total` (points checked, points in the batch), `unconfirmed` (points refused alone that wait for a later point to be written) |
| `last_good_write` | When the store last wrote a data point |
| `quarantine_last` | The newest quarantined points (at most 20, newest first): `tag`, `timestamp` (Unix nanoseconds), `quality`, `seq`, `at` (when it was quarantined) and `error_short` (the store's error) |

The metrics `eaxscada_historian_store_state` (0 ok, 1 isolating, 2 down) and `eaxscada_historian_quarantined_points_total` follow the same state ([metrics](/docs/eaxscada/reference/metrics/#historian)).

**A damaged spool record.** A spool record damaged on disk (its checksum fails, or the file is shorter than written) is cut: the bytes from it on are kept aside in the spool folder (`torn-*.wal`), the points in them are counted lost (`ALM-SYS-HISTORIAN-LOST`, "spool record damaged on disk"), and the records before it and in later files are written in order.

**The system alarm `ALM-SYS-HISTORIAN-STORE-DOWN`** ("Historian store not taking writes", High) is active while the store is down, and clears when it takes writes again. While the store is isolating a point, `ALM-SYS-HISTORIAN-ISOLATING` is active instead (section 2.5f).

**System Health**, Historian storage card:

| Row | What it shows |
|---|---|
| **Logging** | "store not taking writes - points kept in the spool" while the store is down (otherwise "writing", or "paused - disk critically full") |
| **Spool** | shown only when there is something to say: the points waiting with the spool's size of its maximum (for example "350 points waiting (1.2 MB of 2.0 GB)"), the points refused for good and kept in the quarantine, and the store's or the spool's error. While the store is down, its error is shown short: the cause with the store file's name, without its folder (for example `store: ... "scada_history.duckdb" ...`); the full error is in the server log and in `GET /api/historian/storage` (`spool.last_error`, the short one in `spool.last_error_short`) |

`GET /api/historian/storage` carries the same figures in `spool`.

```yaml
historian:
  spool:
    max_size: 2GB        # the default; add it to the historian's disk budget
```

#### When a checkpoint was cut short: repair the file

If the store does not open because a checkpoint was cut short (a power loss or a killed process during a checkpoint), eaxScada checks a copy block by block, recomputes the one wrong checksum, reads every table of the copy and compares its daily row counts with your latest snapshot. Only a copy that passes is offered. An administrator repairs it with an electronic signature. The original file is kept as `scada_history.torn-.duckdb`, a journal is written next to it, and the audit trail records both files' SHA-256 (`HISTORIAN_STORE_REPAIRED`). Your history stays complete and no snapshot restore is needed. Nothing is ever repaired automatically, and an encrypted store is never repaired.

- **The copy and the snapshot are read in a separate process** of the eaxScada program, started by the server for the check, read only, one file at a time, each for at most 6 hours. If that process crashes, hangs or gives no valid answer, the check refuses the repair with the reason, and the server keeps running.
- **At start, the server says at once whether a store that does not open may be repairable**: a warning "historian store at start: may be repairable (a checkpoint cut short)", with the API routes to use, or an information line that it is not a checkpoint cut short and only the set-aside is offered. The start never waits for this check.
- **Copies left by a restart during a check are deleted at start**: `scada_history.repair-.duckdb` and its `.wal` in the store's folder, each deletion logged. They were never put in place; a new check makes a new copy. The kept originals (`scada_history.torn-*`) and every other file stay.

The repair comes before the set-aside: a file that is damaged in any other way can only be set aside. It is available through the [Historian store API](/docs/eaxscada/reference/historian-store-api/#repair-a-file-a-checkpoint-cut-short) too. In System Health, an administrator uses the **Repair...** action next to the store state; it opens a dialog that follows the server's decision for the file:

- **May be repairable:** the dialog offers to check a copy first. The file itself is not changed; the check runs in the background and the dialog follows it.
- **Verified:** the repair on the copy passed, so the dialog offers **Sign and repair**. The signer is the signed-in user, shown read-only; the reason and the password start empty. The dialog then shows what the server did (the original is kept, the repair is signed and journaled).
- **Not repairable, or the check refused it:** **Sign and repair** is disabled and shows the server's reason. Only the set-aside is possible.
- **Set aside instead...** leaves the repair for the set-aside offer at any moment.

How to do it: [Repair a file a checkpoint cut short](/docs/eaxscada/how-to/when-the-historian-store-file-does-not-open/#2a-repair-a-file-a-checkpoint-cut-short).

#### When the store file stays broken: set it aside

A store file that does not open at start is never moved or deleted by itself. When it stays broken, an administrator can set it aside from **System Health > Historian storage > Store file > Set the store aside…** (stores without encryption at rest; offered only while the store did not open at start):

- **The file is checked first.** A file only in use by another process (a second server, a backup tool, an antivirus scan) is not damaged and is refused, as is a file eaxScada may not read or one that opens when checked. Only a file that is not locked, is readable and still does not open can be set aside.
- **Signed and audited.** The signed-in administrator signs with a reason and the password (`historian_store_set_aside`); `HISTORIAN_STORE_SET_ASIDE` is written before the file is renamed, and nothing changes without it.
- **Renamed, never deleted:** the file becomes `scada_history.broken-.duckdb` (with its `.wal`), a new empty store opens in its place, and the spool drains into it: no point waiting is lost.
- **The history before it comes back from a snapshot,** offline: `eaxscada historian-restore --snapshot <file> --keep-current` (see [Restore from a snapshot](#restore-from-a-snapshot)). The snapshots made before the set-aside are kept until then. **How to restore…** names the newest snapshot made before the set-aside.
- **The scheduled export and the nightly snapshot start afresh** on the new store: the errors they recorded while the store did not open are cleared, and both run again at the next minute's check.

How to do it, and what is in neither file: [When the historian store file does not open](/docs/eaxscada/how-to/when-the-historian-store-file-does-not-open/). The routes: [Historian store API](/docs/eaxscada/reference/historian-store-api/).

### 2.5f System alarms of the historian's copies and writes

| Alarm | Severity | Text |
|---|---|---|
| `ALM-SYS-HISTORIAN-STORE-DOWN` "Historian store not taking writes" (new, text changed) | High | The historian's columnar store did not open, or refused a write. New points are kept in the historian spool on disk, in order, and written to the store as soon as it takes them again (retried every minute); none is lost while the spool has room (historian.spool.max_size, 2 GB by default). System Health shows the store's error and the points waiting. It clears when the store takes writes again. It is also active when the historian is isolating a point the store refuses and no point has been written for 30 s: a store that stops taking writes during an isolation is reported down, never as isolating. Since 19 November it is also active, with the same text, when one write to the store has not returned after 30 s, even with no refusal before it; it clears when that write returns and the store takes writes. |
| `ALM-SYS-HISTORIAN-ISOLATING` "Historian isolating a point the store refuses - writing the others" (new) | Medium, no sound | The historian's columnar store refused a batch of points but takes other writes. The historian splits that batch in halves to find the point the store refuses. The other points are written in order. New points wait in the historian spool behind them, and none is lost while the spool has room. Recent trends show the waiting points from memory. The point found is kept in the spool quarantine and counted lost (ALM-SYS-HISTORIAN-LOST). System Health shows the progress, the store's error and the point. It clears when the batch is past. If no point is written for 30 s, the store is reported down instead (ALM-SYS-HISTORIAN-STORE-DOWN). |
| `ALM-SYS-HISTORIAN-BACKUP` "Nightly historian snapshot failed or skipped" (text changed) | Medium | The nightly copy of the historian's columnar store (historian.snapshot) failed, or was skipped because its folder's disk has less free space than the snapshot needs plus the disk guard's critical margin (historian.disk.critical_free). Older snapshots are kept. System Health shows why; the snapshot retries hourly and clears the alarm when one is written. |
| `ALM-SYS-HISTORIAN-LOST` "Historian could not store some points" | High | Section 2.5a. With the columnar store, a refused point waits in the spool and is not lost; it counts here when the spool is full, the point is quarantined, or a spool record is damaged on disk. |
| `ALM-SYS-HISTORIAN-EXPORT` "Scheduled historian export failed" | Low | Section 4.3. |

Their conditions in `eaxscada_system_condition` ([metrics](/docs/eaxscada/reference/metrics/)) are `HistorianStoreDown`, `HistorianIsolating`, `HistorianBackupFailed`, `HistorianPointsLost` and `HistorianExportFailed`. `HistorianStoreDown` and `HistorianIsolating` are never 1 at the same time.

**In the server log**, the historian's storage events (`historian storage: ...`) are logged by what they report:

| Level | Events |
|---|---|
| INFO | a success: a snapshot written, a day exported, logging resumed |
| ERROR | a failure: a failed snapshot, a failed export, logging paused |
| WARN | the rest, such as a purge or a skipped snapshot |

Earlier releases logged every one at WARN or ERROR, the snapshot written every night included.

### 2.6 Configuration (`config.yaml`)

```yaml
# Every edition (the release server)
historian:
  engine: "duckdb"       # the columnar engine; "hive_csv" in builds without the embedded database
  path: "./data/historian"
  tde_encryption:
    enabled: false       # encryption at rest: Enterprise
  retention: 90d
  spool:                 # points the store does not take wait here (section 2.5e)
    max_size: 2GB
  store:                 # the columnar store's memory cap; empty: 25% of the RAM, 512 MiB to 4 GiB
    memory_limit: 1GB    # as shipped in the Linux and Docker packages
    # threads: 2         # empty: one thread per 64 MiB of the cap, at most every core
  snapshot:              # the nightly snapshot, on when the section is absent (section 4c)
    enabled: true
    schedule: "01:30"    # local time
    dir: "./data/backup/historian"
    keep: 2
  export:                # the daily Parquet export: Pro, Enterprise (section 4.3)
    schedule: "02:00"
    dir: "./data/historian_export"
    format: parquet
    compress: true
    # without enabled: on (store without encryption at rest); without keep_days: the retention
```

**Keep a stop or a memory shortage from cutting a checkpoint short.** A process killed during a checkpoint can leave a store file that does not open (section 2.5e). Every DuckDB store of the server therefore has a memory cap, so that together they stay well under the machine's memory and the system does not kill the server to free it. The service units and Compose files also give eaxScada 120 s to stop before it is killed ([Install](/docs/platform/how-to/install/#stopping-without-cutting-a-checkpoint-short)).

#### Memory caps of the stores

**A configured value always wins.** Without one, each store takes its default cap:

| Store | Default cap | Where to set it |
|---|---|---|
| Historian | 25% of the machine's memory, at least 512 MiB, at most 4 GiB (1 GiB when the memory cannot be read) | `historian.store.memory_limit` |
| Genealogy | 1 GiB | `duckdb_memory_limit` in `data/genealogy/settings.json` |
| Alarms, log console, OEE and downtime (`production.duckdb`) | 512 MiB | `production.duckdb.memory_limit` (OEE and downtime only) |
| Audit trail, genealogy states, recipes, security, eaxCollab archive, shift log index | 256 MiB | no key in `config.yaml` |

On Linux, a container's memory limit counts as the machine's memory when it is lower. The configurations of the Linux archive, of the full-build Docker image and of its HA sample set `historian.store.memory_limit: 1GB`; the Windows package's configuration does not set it, so the historian there takes its default. Before this release, a store without a cap could take up to 80% of the RAM, each store of the process its own share.

- **Threads follow the cap.** A store with no threads setting (`historian.store.threads` for the historian) uses one thread per 64 MiB of its cap, at most every core: 8 threads for a 512 MiB store, 4 for a 256 MiB one. With a cap and a thread on every core, each thread had too little memory, and large statements and the checkpoint after them failed. A configured thread count wins.
- **Past its cap, a store spills to disk** instead of failing: to a folder named after its file plus `.tmp`, next to it (`scada_history.duckdb.tmp`, for example). Leave room for it on the store's disk. A store with encryption at rest spills there too, and its spill files are encrypted; before, they went to a `.tmp` folder in the working directory, unencrypted.
- **The start log names each cap**: one line `DuckDB store memory cap` per store, with `memory_limit`, `from` (`config` or `default`), `threads`, `threads_from` and the machine's memory (`physical_mib`).
- **Limit:** a single sort over about 5 to 10 times a small store's cap can still fail, cleanly, with "Out of Memory": the statement fails, and the store stays usable. Raise that store's cap if a query of yours needs it.
- No write-ahead log, sync or checkpoint setting is changed by the caps.

The build decides which engine stores the history: `engine` is written to match it when the configuration is created, and the licence does not change it. The same `historian` section holds the nightly snapshot, the scheduled Parquet export (Pro and Enterprise), encryption at rest (Enterprise) and the disk budget. The [generated configuration reference](/docs/eaxscada/reference/generated/config/server-config/) lists every key.

---

## 3. What gets logged: historian rules

Logging rules are managed by the `ConfigManager` (`internal/historian/config.go`) and configured through the REST API or Dev Studio.

### 3.1 Logging methods

| Method (`method`) | What it logs |
|---|---|
| `ON_CHANGE` (the default) | A value that differs from the last logged one by at least the deadband (`deadband`, absolute or a percentage of the last value, `deadband_type`). With no deadband, every new value. A change of quality class (Good, Uncertain, Bad) or of the simulated marker is logged at once, whatever the deadband (section 3.1b). |
| `PERIODIC` | One sample every `sample_interval_ms` (1000 ms when it is not set), whether the value changed or not. |
| `TRIGGERED` | Only while another tag, the trigger (`trigger_tag_path`), meets the condition (`trigger_condition`: `NON_ZERO`, `EQUAL`, `NOT_EQUAL`, `GREATER_THAN` or `LESS_THAN`, against `trigger_value`). The deadband applies as for `ON_CHANGE`, and so does the quality rule: while the trigger is met, a change of quality class or of the simulated marker is logged at once (section 3.1b). |

The first point of a rule is always logged. A rule that is not enabled logs nothing.

### 3.1a A rule's heartbeat

A value that holds still produces no update, so an `ON_CHANGE` or `TRIGGERED` rule alone would log nothing for as long as the value does not move, and its trend would look empty. The heartbeat, `max_interval_s` (seconds), closes that gap:

- **When the rule has logged no point for `max_interval_s`, the tag's current value is logged again**, with the tag's own quality: a Bad or Uncertain tag is logged as Bad or Uncertain, never as Good. A heartbeat point is logged whatever the deadband.
- **A `TRIGGERED` rule's heartbeat logs only while its trigger is met**, like its other points.
- **`0`, the default, means no heartbeat**: the rule logs as before.
- **Allowed values:** `0`, or 0.5 to 86,400 seconds (a day).
- **Only on a rule for one tag**: a `TAG` rule whose `target_path` names a single tag, with the method `ON_CHANGE` or `TRIGGERED`. A wildcard path (`*` or `.../*`), a `PERIODIC` rule (it samples at its own interval) and an `ALARM` rule are refused with a heartbeat.

In the Studio, **Trends > Logging Policies**, the rule form has a **Heartbeat (seconds, 0 = none)** field next to the deadband; the policies list shows "heartbeat N s" for a rule that has one.

### 3.1b Quality of periodic and triggered samples

- **SAFETY: a change of quality class or of the simulated marker is logged at once under every rule.** When an update's quality class (Good, Uncertain or Bad) or its simulated marker differs from the last point the rule logged for that tag, the update is logged, whatever the deadband: under `ON_CHANGE`, under `TRIGGERED`, and under `PERIODIC` inside its sample interval. The point has the update's time, the value the tag holds and its new quality. Before, a tag that went Bad with its value unchanged logged nothing under an `ON_CHANGE` or `TRIGGERED` rule with a deadband, so its history kept showing the last Good sample.
- **One point per change.** The next updates of the same class and marker go through the deadband as before. A change of code inside one class is not a change: Bad 0x18 to Bad 0x00 goes through the deadband. The class is read from the quality code's major bits (section 5.2).
- **A `TRIGGERED` rule whose trigger is off logs nothing**, a quality change neither. Its first update once the trigger is on again is logged if its quality class or marker differs from the last point it logged.
- **Followed per tag, and not kept across a restart.** A wildcard rule follows each of its tags, so its first update of each tag is logged whatever the deadband. After a restart, each tag's first update under a rule is logged once, whatever the deadband.
- Unchanged: an `ON_CHANGE` rule with no deadband (it logs every new value), tags without a rule (the default policy already logs a quality change at once, section 3.2b), and min/max/average buckets (Good samples only, section 5.3).
- **A periodic sample keeps the tag's own quality**, as change-driven logging does. While a tag is Bad (its device down, its channel disabled) or Uncertain, each periodic sample stores its last value with that Bad or Uncertain code, so trends, history, exports and reports show the period as Bad or Uncertain, never as a Good line at the last value. Earlier releases stored every periodic sample as Good (192); those samples keep the quality they were stored with.
- **A Bad trigger tag never fires a triggered rule.** Its value is not a reading, so the condition is not met and the rule logs nothing while the trigger is Bad. An Uncertain or overridden trigger value still fires; the samples it logs carry their own quality. Bad is read from the quality code's major bits (section 5.2), so a non-standard code of 192 or more whose bits read Bad does not fire either.
- Not sampled at all, as before: a String tag, every tag while the runtime is stopped, and a refused simulated PLC's values.

A query or report that keeps only quality 192 leaves the Bad and Uncertain periods out. See [Show bad and stale values](/docs/eaxscada/how-to/show-bad-and-stale-values/) for how screens and trends draw them.

### 3.2 Deadbands

Deadbands keep electrical noise and sensor jitter out of the history:

- **Absolute deadband:** record the point if `|V_current − V_last| ≥ Deadband`.
- **Percent deadband:** record the point if `|V_current − V_last| / max(|V_last|, 1.0) × 100 ≥ Deadband`.

The deadband applies only while the quality class (Good, Uncertain, Bad) and the simulated marker stay those of the last logged point. A change of either is logged at once, whatever the deadband (section 3.1b).

### 3.2b Tags without a rule

A tag no rule matches is logged by the default policy in `historian.logging` of the server config file. A config file without those keys logs every update the tag engine passes on. A tag whose deadband is 0 then gets a point on every driver poll, even when its value does not change. New installs are written with:

- `default_min_interval: 1s`: at most one point per second per tag. A change inside the second is held, and its latest value is written when the second ends, so the last value of a step is never lost.
- `default_deadband: 0`: log changes only. A repeated identical value is not logged.
- `default_max_interval: 10m`: a steady value still gets a point every 10 minutes, so its trend is never empty.

`default_max_interval` is a heartbeat: when a tag the default policy logs has had no point for that long, its current value is logged with its own quality, even when no update arrives (a steady value produces none). At most one such point per tag per interval. A tag a rule matches is not logged by the default policy: the rule decides, and its own heartbeat (section 3.1a) applies. `0` or no key: no heartbeat. Before this release, the point was written only when an update arrived after the interval, so a tag that held still got none.

A quality change is always logged at once. The System Health history (`System/Health/...`) keeps every sample. See [Keep the historian within its disk budget](/docs/eaxscada/how-to/keep-historian-within-disk-budget/).

### 3.3 Rule API

| Endpoint | Method | Description |
|---|---|---|
| `/api/historian/configs` | `GET` | All logging rules with runtime statistics (log count, last logged timestamp). |
| `/api/historian/configs` | `POST`, `PUT` | Creates or updates a rule. |
| `/api/historian/configs/:id` | `GET` | One rule. |
| `/api/historian/configs/:id` | `DELETE` | Deactivates and removes a rule. |

A rule with a heartbeat out of its bounds (section 3.1a) is refused with `400` and an error that names `max_interval_s`; nothing is stored. A rule saved through the API is stored as its own copy: nothing the caller does with its request afterwards changes the live rule. The partition list of the Hive export settings is copied the same way.

#### Rule definition

```json
{
  "id": "hist_reactor1_temp",
  "target_type": "TAG",
  "target_path": "Plant/Line1/Reactor1/Temperature",
  "description": "Reactor 1 Core Temperature - On Change with 0.2°C Deadband",
  "method": "ON_CHANGE",
  "deadband": 0.2,
  "deadband_type": "ABSOLUTE",
  "sample_interval_ms": 1000,
  "max_interval_s": 600,
  "enabled": true
}
```

`max_interval_s` is the heartbeat (section 3.1a); without it, or with `0`, the rule has none.

---

## 4. Hive-partitioned Parquet export (Pro, Enterprise)

Parquet is the standard columnar file format of enterprise data lakes, and the columnar engine writes it natively.

### Which editions export

The analytics export (Parquet files in Hive partitions, by day) is part of Pro and Enterprise, and of the Free evaluation. Starter keeps the historian itself.

- **On Starter, starting or configuring an export is refused** with `403` and code `EDITION`: `POST` and `PUT /api/historian/export/config`, `POST /api/historian/export/run` and `POST /api/historian/export/scheduled`.
- **Still available in every edition:** reading history, reading the export configuration and the list of partitions already exported.
- **The scheduled export does not run** on an edition without the analytics export. This is logged once.
- **After a downgrade, files already exported stay as they are.** They are not removed by `keep_days`; only new exports stop.
- **Studio, Trends > Export by day:** on Starter it shows the export settings and the days already exported, read only, with "Analytics export needs Pro or Enterprise". **Export now** and **Save Default Settings** are offered on Pro, Enterprise and Free (evaluation).

### 4.1 Directory layout

Exports use Hive-style partition folders, one folder per UTC day. The scheduled export (section 4.3) writes to `historian.export.dir` (`./data/historian_export` by default), one file per closed day:

```
data/historian_export/
└── year=YYYY/
    └── month=MM/
        └── day=DD/
            └── data.parquet      (data.csv or data.csv.gz with format csv)
```

### 4.2 Running an export

The on-demand Parquet export writes to its own folder, `config/hive_export` under the historian folder by default (not the scheduled export's folder):

```sql
COPY tag_history TO 'data/historian/config/hive_export'
(FORMAT PARQUET, PARTITION_BY (year, month, day), OVERWRITE_OR_IGNORE);
```

Analytics platforms can mount the Parquet folder directly as external tables, with no conversion pipeline.

### 4.3 Scheduled export of closed days

`historian.export` in the server config file exports each closed UTC day once, every day at its `schedule` (local time, 02:00 by default). Each day becomes `<dir>/year=YYYY/month=MM/day=DD/data.parquet` (zstd-compressed), or `data.csv` / `data.csv.gz` with `format: csv`. The default folder is `./data/historian_export`.

**On by default, as a second copy of the history.** In the editions with the export (section "Which editions export"), with the columnar store and without encryption at rest, the export runs when the config file does not set `enabled`. It is the history's second copy, beside the nightly snapshot (section 4c):

- **Without `keep_days`, it keeps the historian's retention** (whole days; an unlimited retention keeps every exported day), so the export mirrors the history.
- **A file that sets `enabled` or `keep_days` keeps what it says.** New installs' config files no longer write either key.
- **Config files written by earlier releases** hold the export section the reference file wrote: `enabled: false`, `schedule: "02:00"`, `dir: "./data/historian_export"`, `format: parquet`, `keep_days: 0`, `compress: true`. Left exactly as written, that section reads as unset, so the export comes on, and the server logs at start "daily history export now on by default; set historian.export.enabled: false to keep it off". A section with any value changed or any key removed keeps what it says. To keep the export off, see [Keep the export off](#keep-the-export-off).
- **An encrypted store is not exported:** its export would be plain text. Its second copy is the snapshot, which is encrypted with the store's key.
- **Starter does not export** (the export is a Pro and Enterprise feature): Starter's second copy is the nightly snapshot.

**The first run** exports every closed day still in the history, one after the other, once. On the reference workstation it writes about 5 million rows a second (about 10 bytes a row on disk): about **18 s per day of history at 1,000 tags/s**, so about 30 minutes for 90 days and about 2 hours for a year. Stopped by a restart or a low disk, it resumes with the days not exported yet. Only one run goes at a time.

The export also:

- never exports the current day;
- never writes a day again unless forced: `_export_manifest.json` in the folder records each exported day;
- writes each file beside its final name and renames it, so a file is complete or absent;
- **skips a day when the disk is low:** when the export folder's disk has less free space than the day's estimated size plus the disk guard's critical line (`historian.disk.critical_free`, where it purges or pauses), the day is not written, the system alarm `ALM-SYS-HISTORIAN-EXPORT` ("Scheduled historian export failed", low) says why, and the next run tries again;
- refuses a destination on a critically full disk, and raises `ALM-SYS-HISTORIAN-EXPORT` when it fails. System Health's **Export error** row shows the short cause (the store file's name, no folder path, no driver prefix); the full error is in the server log and in the export status (`last_error`, with `last_error_short` beside it);
- reads a day's CSV history in write order (`data.csv`, then `late.csv`, rows in file order), with the columnar store's value where it holds the same tag and timestamp;
- removes its own day folders older than `keep_days`, or than the retention without it.

The audit trail records every run. `POST /api/historian/export/scheduled` runs it at once (`{"force": true, "day": "2026-10-07"}` exports one day again).

#### Keep the export off

In the config file, write the export section with `enabled: false` and at least one difference from the old generated section, for example only the key itself:

```yaml
historian:
  export:
    enabled: false
```

An old generated section left exactly as written turns the export on, even though it says `enabled: false`; removing its other lines, or changing any value, keeps it off. Restart the server and check that the start log no longer says "daily history export now on by default".

## 4b. Retention and the disk budget

The historian deletes whole UTC days older than `historian.retention`, from the CSV partitions and the columnar store together. A pattern in `retention_overrides` can keep some tags longer or shorter. Today and yesterday are never deleted, nor are the two newest days that hold data, so a clock jump cannot expire the whole history. `historian.max_size` and the free-space lines in `historian.disk` purge the oldest days first, and pause logging while the disk stays critically full. Every purge is in the audit trail, and `GET /api/historian/storage` shows what the retention would delete now without deleting anything. The how-to [Keep the historian within its disk budget](/docs/eaxscada/how-to/keep-historian-within-disk-budget/) walks through the settings.

The retention reads a CSV folder's rows only where it needs the tag paths: for a tag with a shorter per-tag retention, on days past it. Every other CSV folder is kept to the longest retention configured, which is what the global retention and the disk budget purge by. On a store of 1,000 tags over a year, the hourly inventory used to open every folder's files and took more than 30 minutes on a Windows workstation; a later inventory now reads no file until one changes. Purge records count tags by folder name. A folder shared by two tag paths (section 2.3) is kept until the longest retention, never deleted early.

## 4c. Second copies of the history, and restoring them

The columnar store must never be the only copy of the history. Two copies are made by default:

| Copy | Editions | What it holds | Restore |
|---|---|---|---|
| **Nightly snapshot** | every edition with the columnar store, encrypted stores included | the whole columnar store, the last 2 nights | replaces the whole store |
| **Daily Parquet export** (section 4.3) | Pro, Enterprise and the Free evaluation, without encryption at rest | one Parquet file per closed day, for the retention | adds only the points the store lacks |

**Diagram: The second copies of the history, and what a restore brings back** (timeline)

Each night at 01:30 a snapshot copies the whole columnar store, and at 02:00 the export writes one Parquet file for each closed UTC day; the open day is never exported. Retention removes whole UTC days from the store; the copies have their own limits. A restore from the snapshot replaces the store and loses what was written after it; after a set-aside, --keep-current keeps the newer rows but the time between the snapshot and the set-aside is in neither; --from-export adds only points the store lacks.

Time runs left to right: closed UTC days, then today. The lengths are not to scale.

**Each night**

- **Columnar store**: whole UTC days purged (new). Where the store was set aside, a new store holds what is written from then on. Retention runs every hour and removes whole UTC days older than the retention, from the store only.
- **Snapshot**: 01:30, whole store, keep 2 (whole store; verified). The copy is verified by its rows per closed UTC day before the oldest snapshots beyond two are removed.
- **Export**: 02:00, a file per day. On by default on a build with the columnar store and no encryption at rest, in the editions with the analytics export. Files are kept for the retention by default. The open day is never exported.

**What a restore brings back**

- 1. **--snapshot**: replaces the whole store (lost). History written after the snapshot is not in it. The previous store is kept beside it as a before-restore folder.
- 2. **--snapshot --keep-current**: the gap is in neither. The current store's rows are appended after the snapshot's; history written between the snapshot and the set-aside is in neither.
- 3. **--from-export**: adds what the store lacks (closed days only). Only the tag and timestamp pairs the store has no row of are added; the store's rows are never changed.

The snapshot holds the whole store as of 01:30; the export holds closed days only. What was written since the snapshot is in neither.

### The nightly snapshot

Every night at `historian.snapshot.schedule` (01:30 local time) the historian copies its columnar store to `<dir>/historian-.duckdb`, with a record `<file>.json` beside it. It is on by default, also in existing config files without the `snapshot` section.

- **Once a day, restarts included.** At start the server takes the last run from the newest snapshot in the folder (its record, else the time in its name), so a restart after today's snapshot takes none. A snapshot missed while the server was off is still taken at the next check. Before, every start after the scheduled time took a new snapshot, and with `keep: 2` a few restarts in a day pruned the snapshots of the days before.
- **Consistent, while logging goes on.** The copy is made without stopping the historian.
- **Verified before it counts:** its rows per closed UTC day must equal the store's. A copy that does not read back as the store is refused after one retry, and no file of it is kept.
- **Written beside its final name and renamed**, so a snapshot is complete or absent.
- **Encrypted with the store's own key** when the store uses encryption at rest.
- **2 kept by default** (`keep`). Each is about the size of the store. The oldest beyond `keep` are deleted once a new one is verified; only files the snapshot wrote (its name pattern and its record) are deleted, and a bad copy never pushes out a good one.
- **Same disk by default.** `./data/backup/historian` is on the historian's disk: the snapshot protects against a damaged store, not against a lost disk. Point `dir` at another disk for that.
- **The columnar store only.** A snapshot does not hold the CSV partitions.

**Low disk.** A snapshot is skipped, before anything is written and without deleting an older one, when its folder's disk has less free space than the estimated size (the store's used blocks and its write-ahead log) plus the disk guard's critical line (`historian.disk.critical_free`). It is retried hourly, and the skip says "…plus the disk guard's critical margin of X". Earlier releases used the warning line (`historian.disk.warn_free`): a disk under the warning line, a common state, never got a snapshot and `ALM-SYS-HISTORIAN-BACKUP` stayed on. **The disk guard comes first:** when the historian's disk becomes critically full during a copy, the copy is stopped, leaves no file and is recorded as "skipped: the historian's disk is critically full", and the guard's emergency purge runs at once.

**Alarm and audit.** The system alarm `ALM-SYS-HISTORIAN-BACKUP` ("Nightly historian snapshot failed or skipped", medium) is active while the last attempt failed or was skipped, and clears when a snapshot is written. The audit trail records each snapshot, skip and failure (`HISTORIAN_SNAPSHOT`, `HISTORIAN_SNAPSHOT_SKIPPED`, `HISTORIAN_SNAPSHOT_FAILED`). `GET /api/historian/storage` and System Health show the snapshot's state (`snapshot`).

```yaml
historian:
  snapshot:
    enabled: true
    schedule: "01:30"              # local time
    dir: "D:/eaxscada-backup/historian"   # another disk: protects against a lost disk too
    keep: 2
```

### Restore from a snapshot

With the server stopped, run a dry run first, then the restore:

```sh
eaxscada historian-restore --snapshot ./data/backup/historian/historian-.duckdb
eaxscada historian-restore --snapshot ./data/backup/historian/historian-.duckdb --confirm
```

- **Without `--confirm` it is a dry run:** it checks the snapshot and prints what it would do, and writes nothing.
- **It replaces the whole columnar store** with the snapshot's, through the same staging copy, swap and audit record (`HISTORIAN_SNAPSHOT_RESTORED`) as an archive restore. The previous historian folder is kept beside it, unchanged.
- **History written after the snapshot is not in it**, and no CSV copy holds it either (no CSV is written next to the columnar store). A tag the snapshot holds no row of keeps reading its CSV history from before the columnar store. The dry run says how many rows of the current store the restore would drop.
- **`--keep-current` keeps the current store's rows:** they are appended after the snapshot's in their write order (later writes: they win where both hold a tag and timestamp), and checked by count and checksum before the swap. This is the restore after the store file was [set aside](/docs/eaxscada/how-to/when-the-historian-store-file-does-not-open/): the new store holds the points written since. History written between the snapshot and the current store's first point is in neither (only in the broken file); the dry run says so. Stores without encryption at rest only.

```sh
eaxscada historian-restore --snapshot "./data/backup/historian/historian-.duckdb" --keep-current
eaxscada historian-restore --snapshot "./data/backup/historian/historian-.duckdb" --keep-current --confirm
```

- **After a set-aside, use a snapshot made before it.** System Health's **How to restore…** names the newest of them and shows the command. Those snapshots are never pruned while the set-aside record (`scada_history.set-aside.json`) is there, and they do not count towards `keep`; a snapshot restore removes the record.
- **A restore writes the columnar store only**, never CSV partitions (this holds for every `historian-restore`).

### Import from the daily export

With the server stopped, import the export's Parquet days back into the historian, again with a dry run first:

```sh
eaxscada historian-restore --from-export ./data/historian_export --from 2026-10-01 --to 2026-10-31
eaxscada historian-restore --from-export ./data/historian_export --from 2026-10-01 --to 2026-10-31 --confirm
```

- `--from` and `--to` (UTC days, `YYYY-MM-DD`) are optional: by default, the export's first and last day.
- **Only the points the store has no row of are added** (a tag and timestamp pair it lacks); of two writes of one pair in the file, the later. The store's own rows are never changed, so **a second import adds nothing**.
- It goes through the restore's staging copy, swap and audit record (`HISTORIAN_EXPORT_IMPORTED`); the previous folder is kept.

### The notice file after a restore or an import

After an archive restore (`eaxscada historian-restore <file.eaxhistory>`), an import from the daily export (`--from-export`) or a [CSV history import](/docs/eaxscada/how-to/import-csv-history-into-the-store/) (17 November), the historian folder may hold a small file `scada_history.bulk-notice.json`. **This is expected: do not delete, move or edit it.**

- It lists the time ranges the restore or the import wrote, one per tag (every tag at once when more than 1,000 tags were written, or when the store uses encryption at rest, so that no tag name is kept in a plain file). It holds no values.
- It is written after the rows are committed, beside its final name and renamed, so it is complete or absent.
- The server reads it at a later start, uses it to bring what it computes from the history up to date for those ranges, and removes it itself. It may stay in the folder until then.
- It changes nothing in the history itself: trends, reports and exports read the store as before. A snapshot restore and the retention purge leave no such file.

The [command-line reference](/docs/eaxscada/reference/generated/cli/#scada-server-historian-restore) lists every flag of `historian-restore` and `historian-backup`.

---

## 5. SQL queries and downsampling

Free SQL over the history table runs through the read-only historian tool `scada_query_historian`, for AI assistants (the MCP gateway) and for integrations (`POST /api/mcp/tools/call`), and only for accounts that may read every tag ([who may run it](/docs/eaxscada/explanation/mcp-ai-gateway/#7-read-only-historian-queries)). For averages, minimums and maximums, keep only Good samples with the good-quality filter:

```http
POST /api/mcp/tools/call
Content-Type: application/json

{
  "name": "scada_query_historian",
  "arguments": {
    "sql_query": "SELECT tag_path, avg(value) AS avg_val, max(value) AS max_val FROM tag_history WHERE timestamp >= 1726240000000000000 AND (quality % 256) >= 192 AND quality <> 512 GROUP BY tag_path"
  }
}
```

The answer is `{"result": {"row_count", "rows", "row_limit", "warning"}}`; `warning` is there only when the query ignores quality (section 5.4).

### 5.1 Downsampling

Trending long windows (30 days of 100 ms telemetry is 25,920,000 points) would exhaust browser memory if raw points were sent. eaxScada reduces history in two ways:

- **Trends** (the Historian workspace, dashboard trends, gauge sparklines) get a thinned set of real samples that keeps the shape of the curve: peaks, steps and every change of quality survive (section 5.2). Millions of points become 500–1,000 points that the trend draws instantly.
- **Min/max/average buckets** are what the AI assistant reads with `scada_query_tag_history` when it asks for buckets. Each bucket covers a fixed time span and gives the sample count, the minimum, maximum and average, and the first and last sample. These values are worked out from **Good samples only** (section 5.3).

### 5.2 Quality in trends and downsampled history

Every trend (the Historian workspace, dashboard trends, gauge sparklines) draws quality as it is, never as Good:

| Quality | How the trend draws it |
|---|---|
| Good | a solid line |
| Uncertain, and overridden (an operator's value) | a dashed segment |
| Bad | a gap with a shaded band |

**The rule.** A stored quality code is classed by its OPC major bits, the same way the tag engine names a quality:

| Major bits of the code (`code & 0xC0`) | Class |
|---|---|
| `0xC0` | Good |
| `0x40` | Uncertain |
| `0x00` or `0x80` | Bad |

The one exception is the overridden code `0x0200` (a value an operator entered in place of the field reading): it is classed **Uncertain**. It is a value, so not Bad, but it is not a Good reading from the field either.

What this changes compared with earlier releases, which counted every code of 192 or more as Good:

- **Overridden values are Uncertain in long trends.** A short overridden spell used to disappear when a long period was downsampled, and the period was drawn as a Good line. It is now kept and drawn dashed.
- **Odd codes are no longer drawn as Good.** A non-standard code of 192 or more whose major bits read Bad or Uncertain (for example `0x0100`) is drawn as Bad or Uncertain.
- **Short spells survive downsampling.** When a long trend is thinned, the start and end of every run of one quality are kept, and every sample of a Bad, Uncertain or overridden run of up to three samples is kept, so a brief loss of signal or a brief manual value still shows on a 30-day trend.
- **Stored samples are unchanged.** Their values and quality codes are as they were written; only how they are classed when drawn changes. A query that keeps only quality 192 still leaves the overridden, Bad and Uncertain periods out.

#### How long a sample holds

A tag logged on change has one sample when it changes, then none until it changes again. A trend draws each sample until the next one:

- **A Bad sample stays Bad until the pen's next sample.** Its shaded band runs to that sample. A Bad last sample runs to now on a live trend, while the live link is up ([When the live link goes down](#when-the-live-link-goes-down)); to the end of the read on the History page (`/history`) and in the Studio's **Trends**; to the end of the range on a dashboard card, never past now; and to the end of a report's range, never past the time the report runs.
- **A Bad reading without a value is a Bad sample**, never a plain gap: a live update, a history sample, or a bucket with no Good sample. The line is never joined across it.
- **A Good or Uncertain value holds until the next sample.** When the line does not join a sample to the next one (the next is Bad, has no value, or there is none), the value is drawn as a lighter flat line: solid when Good, dashed when Uncertain. It runs to the next sample, or to the same end as a Bad band. It never runs across a Bad span, into a stretch with no data, or past now. Line pens only: a bar pen draws each sample as a bar.
- **Each recorded sample has a dot** on a line pen of up to 300 samples. On a denser pen, only the samples a held line starts from have one. The end of a held line has no dot: it is not a sample.
- **A live trend is redrawn every 5 s** while its page is visible, so a held value and a Bad band follow now. Nothing is read again. A hidden browser tab is redrawn once, when it is shown again. The History page shows its read and is not redrawn.
- **The Values tab** of a trend says **Bad** in the cell of a Bad sample, never a dash. Inside a Bad span, the rows of the other pens show the pen as "Bad · 10:42:05", the time the span began. A row with a Bad pen has a rose accent, and an Uncertain value is marked "(Uncertain)". The CSV export writes the same words.
- **The History page marks simulated samples**: a violet SIM band in the chart, and a **Source** column (plant or simulated) in the samples table and its CSV. A sample without a value shows "—" in the **Value** column, never 0.000.

#### When the live link goes down

A live trend gets its live samples over the browser's live link, the `/ws` socket. While that link is down no sample reaches the trend, so it draws none that never arrived (29 November):

- **The trend stops where the link went down.** The line, a held value, and the Bad or SIM band of the last sample end at that moment. They go on only once the values are in again after the reconnect: the server's answers for the trend's tags, or the first live sample. No line, held value or band crosses the outage, before or after the link is back.
- **A grey band covers each span the link was down**, labelled "Live link down", and the tooltip inside it says so. The band stays after the link is back, as long as the span is in the trend's window. While the link is down, an amber **Live link down** chip shows in the trend's top row.
- **A link that goes silent counts from its last frame.** A socket that stays open while nothing reaches it is found 20 to 24 s after its last frame, and the span starts at that frame, not at the detection ([A link that goes silent](/docs/eaxscada/reference/live-data-socket/#a-link-that-goes-silent)).
- **The Studio's Trends fills the span with what the historian logged.** Trends reads the history again at each refresh (every 5 s by default), and that read holds the samples the server logged while the browser's link was down. They are drawn as recorded inside the band: lines, held values and Bad bands between them. The parts of the span that no logged sample covers keep no line or held value: nothing is held across them from the last sample before the outage.
- **Which trends.** The screen trend, the classic dashboard trend card, the **Trend with values** (Chart | Values) and the Studio's **Trends**. Of these, only the Studio's Trends reads the history again: the others keep the span empty. The History page, report trends and the dashboard cards that read by query do not follow live values and are not marked. A page without the live link is drawn as before.

To read the sample a range opens with, see [5.5 The sample before a range](#55-the-sample-before-a-range).

### 5.3 Quality in min/max/average buckets

A minimum, maximum or average is a single number: once worked out, nobody can see that a Bad reading or an operator's value went into it. The AI assistant reports these numbers to people, so eaxScada never averages non-Good data in.

**Only Good samples are used.** The minimum, maximum and average of a bucket are worked out from its Good samples only, using the rule in section 5.2. Uncertain, Bad and overridden samples are counted, but never averaged in. **A bucket with no Good sample has no average**, and no minimum or maximum: these fields are empty (`null`), never an average of Bad or overridden values.

**Each bucket says how good it is.** Its `quality` is one of:

| Bucket quality | Meaning |
|---|---|
| `good` | every sample in the bucket is Good: the minimum, maximum and average are plain readings |
| `uncertain` | some samples are Uncertain or overridden, or some are Bad beside Good ones: the values come from the Good samples only, and the rest were left out |
| `bad` | every sample in the bucket is Bad: there is no minimum, maximum or average |

Beside it, `good_count`, `uncertain_count` and `bad_count` say how many samples of each kind the bucket holds; `count` is still every sample. **An overridden value** (a value an operator entered in place of the field reading) **counts as Uncertain, never Good**, so it is never part of the average.

**First and last** are the bucket's first and last samples whatever their quality; `first_quality` and `last_quality` say whether each was good, uncertain or bad.

**What the AI assistant is told.** The history tool tells the assistant that an uncertain or bad bucket is not a plain reading, and that it must report it as uncertain or bad, with its counts, never as a normal value. Each tag's answer also says how many of its buckets are not good (`buckets_not_good`). See [the AI gateway's historian queries](/docs/eaxscada/explanation/mcp-ai-gateway/#7-read-only-historian-queries).

:::note[Changed in this release]
The minimum, maximum and average used to be worked out from every sample in the bucket, whatever its quality, so a Bad value or an overridden value could be reported as a normal average. Integrations reading these buckets must now handle an empty (`null`) average, minimum and maximum, and can read the new quality fields; no field was removed.
:::

### 5.4 Quality in free SQL answers

Free SQL returns **every sample**, Bad and Uncertain ones too, and eaxScada **never rewrites the query**: what you get is what the SQL asks for. Instead, the answer says how good each row is, and warns when the query did not look at quality:

- **Each row carries its quality class.** A row that holds a sample's quality code gets `quality_class` beside it: `good`, `uncertain` or `bad`, by the same rule as trends (section 5.2: an overridden value is `uncertain`). A quality column under another name gets `<alias>_quality_class` (for example `q_quality_class` for `quality AS q`). A column of your own already named `quality_class` is never overwritten.
- **A query that reads `value` without looking at quality gets a `warning`.** When the query reads `value` but neither selects `quality` nor uses it in a filter (`WHERE`, `HAVING`, a join condition, an aggregate `FILTER`, `CASE WHEN` or `GROUP BY`), the answer carries:

  ```text
  this query ignores sample quality; bad and uncertain samples are included — add the good-quality filter: (quality % 256) >= 192 AND quality <> 512
  ```

  Such a result is unchecked: Bad and Uncertain samples are in it as plain numbers. Do not report it as a plain reading.
- **Queries that filter on quality are answered as before**, with no warning.

The good-quality filter, for any average, minimum or maximum:

```sql
SELECT avg(value), min(value), max(value)
FROM tag_history
WHERE tag_path = 'Plant/Processing/BlendLoop/Flow'
  AND (quality % 256) >= 192 AND quality <> 512
```

`(quality % 256) >= 192` keeps the codes whose major bits read Good, and `quality <> 512` leaves out the overridden code `0x0200` (an operator's value). To see what was left out, select `quality` too: every row then says its `quality_class`.

:::note[Changed in this release]
Free SQL used to return Bad and Uncertain samples as plain values, with nothing in the answer to say so. The rows and the SQL are unchanged; `quality_class` (or `<alias>_quality_class`) and `warning` were added, and no field was removed.
:::

### 5.5 The sample before a range

Under an `ON_CHANGE` rule, a tag that has been Bad, or steady, for longer than a range has no sample inside it. A read of the range alone answers nothing for it, which looks like "no data". Its last sample before the range is the state the range opens with. Three reads can return it on request:

| Read | Ask with | What comes back |
|---|---|---|
| `GET /api/history` | `prior=1` (also `true`; `0` or `false` is the default) | Each tag's points are led by its last point before `from`, marked `"before": true`. The answer has the header `X-History-Prior: true`. |
| `scada_query_tag_history` (MCP) | `"include_before": true` (default `false`) | Each tag's entry gets `before`: `timestamp_iso`, `value`, `quality` and `quality_class`, with raw points and with buckets. |
| `POST /api/dashboards/query` | nothing: always for history and aggregated history | Each frame's `meta.before`: `timeMs`, `value` (`null` when not a number), `quality` (`good`, `uncertain` or `bad`) and `simulated`. See [The sample before the range](/docs/eaxscada/reference/dashboard-cards/#the-sample-before-the-range). |

The rules are the same for the three:

- **The latest sample strictly before the start of the range.** A sample at the start itself is in the range. There is no time bound: a tag Bad for a month is carried into a one-hour range. Only the retention limits it.
- **Only with a complete answer.** When the range's samples were cut by the limit (or the dashboard answer is truncated), the answer has no sample before: it would bridge the samples left out.
- **A tag without a sample before the range** gets none. A read without a start (no `from` or `minutes`) gets none.
- **When the history store does not answer**, the whole read fails as before (`503 history_unavailable`, an error from the tool), never an answer without the sample before.
- **Without the parameter, the answers are unchanged.** `/api/history` refuses a `prior` that is not true or false (`400`, "prior must be true or false (1 or 0)").

The aggregated dashboard frames also carry `last_quality` beside `quality`: the class of each bucket's last sample. A bucket where the tag went Bad after Good samples is `uncertain`, with a Good average; its `last_quality` `bad` says the tag is Bad from there on, until the next bucket.

No screen or card draws the sample before yet: the trends draw what the range holds ([How long a sample holds](#how-long-a-sample-holds)).

---

## 6. See also

- [Alarms](/docs/eaxscada/explanation/alarms/): the ISA-18.2 alarm lifecycle and the SOE journal.
- [Security and 21 CFR Part 11](/docs/platform/explanation/security-and-part-11/): signatures and audit of historian-relevant actions.
- [MCP AI gateway](/docs/eaxscada/explanation/mcp-ai-gateway/): governed, read-only historian queries from AI assistants.
- [Import the CSV history into the store](/docs/eaxscada/how-to/import-csv-history-into-the-store/): move CSV partitions of an upgraded install into the columnar store, from System Health or the command line.
- [Historian CSV import API](/docs/eaxscada/reference/historian-csv-import-api/): the routes behind System Health's import.
- [When the historian store file does not open](/docs/eaxscada/how-to/when-the-historian-store-file-does-not-open/): locked or damaged, set a damaged file aside, restore the history before it.
- [Historian store API](/docs/eaxscada/reference/historian-store-api/): the routes behind "Set the store aside…".
