Skip to content

A TIMESERIES type whose TIMESTAMP column is not declared first round-trips through JSONL with its values in the wrong columns #7899

Closed

Description

@rspereiratech

Summary

The engine's positional row format is fixed: TimeSeriesBucket.readRow writes result[0] = <timestamp> and
then the NON-timestamp columns in schema order ("First element is always the timestamp"). That is the layout
every read path receives, including TimeSeriesEngine.forEachRow. PromQLEvaluator states the rule
explicitly and maps around it.

JsonlExporterFormat.exportTimeSeries does not. It writes sample[i] = row[i] and documents the result as
"the raw value array the engine reads and writes, in schema-column order, timestamp first" - two descriptions
that only coincide when the TIMESTAMP column happens to be schema column 0.
JsonlImporterFormat.loadTimeSeriesSamples then reads the array the other way, taking the timestamp from
sample.get(timestampIdx) where timestampIdx is the TIMESTAMP column's position IN THE SCHEMA.

Until yesterday a type could not easily be in that state through SQL: the grammar had one TIMESTAMP slot
ahead of one TAGS slot and one FIELDS slot. Issue #7702 turned the column members into one repeatable list
precisely so "a declaration whose timestamp is not the first column [can] be spelled at all" (grammar
comment, SQLParser.g4), and CreateTimeSeriesTypeStatement now inserts the TIMESTAMP column at
timestampPosition. So the new grammar makes reachable a type for which the JSONL round trip is wrong.

Two outcomes, depending on the column that precedes the timestamp:

  • a STRING column before it: the restore dies with a bare ClassCastException: String cannot be cast to Number out of loadTimeSeriesSamples, i.e. the export cannot be restored at all;
  • a NUMERIC column before it: no error. The timestamp is stored as that column's value and that column's
    value is stored as the timestamp. Retention, compaction bucketing, downsampling, range scans, latest,
    PromQL and every /ts read then operate on a timestamp the data never had.

Where (HEAD 06b033d)

engine/src/main/java/com/arcadedb/engine/timeseries/TimeSeriesBucket.java:1501 - the contract

  private Object[] readRow(final BasePage page, final int rowOffset, final int[] columnIndices) {
    // First element is always the timestamp
    final int resultSize = columnIndices != null ? columnIndices.length + 1 : columns.size();
    final Object[] result = new Object[resultSize];
    result[0] = page.readLong(rowOffset);
    ...
      for (int c = 0; c < columns.size(); c++) {
        if (columns.get(c).getRole() == ColumnDefinition.ColumnRole.TIMESTAMP)
          continue;
        result[colIdx + 1] = readColumnValue(page, colOffset, columns.get(c), colIdx);

integration/src/main/java/com/arcadedb/integration/exporter/format/JsonlExporterFormat.java:328 - the writer

          engine.forEachRow(Long.MIN_VALUE, Long.MAX_VALUE, null, null, null, row -> {
            final JSONArray sample = new JSONArray();
            for (int i = 0; i < columns.size() && i < row.length; i++)
              sample.put(NonFiniteNumbers.encode(row[i]));

with the javadoc above it claiming "in schema-column order, timestamp first".

integration/src/main/java/com/arcadedb/integration/importer/format/JsonlImporterFormat.java:576-611 - the reader

    int timestampIdx = 0;
    for (int i = 0; i < columns.size(); i++)
      if (columns.get(i).getRole() == ColumnDefinition.ColumnRole.TIMESTAMP) {
        timestampIdx = i;
        break;
      }
    ...
      timestamps[r] = ((Number) sample.get(timestampIdx)).longValue();
      int valueIdx = 0;
      for (int c = 0; c < columns.size(); c++) {
        if (c == timestampIdx)
          continue;
        values[valueIdx][r] = decodeSampleValue(sample.get(c), columns.get(c).getDataType());
        valueIdx++;
      }

The same positional confusion sits in the SQL read path, which is how the corruption stays invisible after a
restore (the two errors cancel for a plain SELECT):
engine/src/main/java/com/arcadedb/query/sql/executor/FetchFromTimeSeriesStep.java:147

            for (int i = 0; i < columns.size() && i < row.length; i++) {
              final ColumnDefinition col = columns.get(i);
              Object value = row[i];
              ...
              result.setProperty(col.getName(), value);
            }

Compare engine/src/main/java/com/arcadedb/engine/timeseries/promql/PromQLEvaluator.java:688-700, which gets
it right and says why: "The row format is always [timestamp, non-ts-col-0, non-ts-col-1, ...], so we iterate
non-TIMESTAMP columns and map them to row positions 1, 2, 3... regardless of where the TIMESTAMP column
appears in the schema definition."

Repro

Embedded, against this build's classes.

  1. The SQL read alone (no export involved):
db.command("sql", "CREATE TIMESERIES TYPE M TAGS (host STRING) TIMESTAMP ts FIELDS (v DOUBLE)");
db.command("sql", "INSERT INTO M SET ts = 1700000000000, host = 'srv-1', v = 42.5");
db.query("sql", "SELECT * FROM M");

prints

SELECT row -> {"host":1700000000000,"ts":"srv-1","v":42.5}

The INSERT is correct - SaveElementStep.saveToTimeSeries reads each column BY NAME - so this is purely the
read mapping columns onto the wrong row positions.

  1. The export, same type, one sample:
{"t":"schema", ... "tsColumns":[{"name":"host",...,"role":"TAG"},{"name":"ts",...,"role":"TIMESTAMP"},{"name":"v",...,"role":"FIELD"}]}
{"t":"ts","c":{"t":"M","s":[[1700000000000,"srv-1",42.5]]}}

The schema line records the declared order correctly; the sample array is timestamp-first, so it does NOT
follow it.

  1. Restoring that export into a fresh database:
SEVER [JsonlImporterFormat] Error on importing 'ts' record: {"t":"ts","c":{"t":"M","s":[[1700000000000,"srv-1",42.5]]}}
java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Number
	at com.arcadedb.integration.importer.format.JsonlImporterFormat.loadTimeSeriesSamples(JsonlImporterFormat.java:603)
  1. The silent variant - a numeric column before the timestamp - exported and restored, then the engine rows
    read directly (LocalTimeSeriesType.getEngine().query(Long.MIN_VALUE, Long.MAX_VALUE, null, null), whose
    layout is timestamp-first by definition):
CREATE TIMESERIES TYPE N FIELDS (seq LONG) TIMESTAMP ts FIELDS (v DOUBLE)
INSERT INTO N SET ts = 1700000000000, seq = 7, v = 42.5

SOURCE   engine row (ts first) = [1700000000000, 7, 42.5]
RESTORED engine row (ts first) = [7, 1700000000000, 42.5]

The restored series carries timestamp 7 (1970-01-01T00:00:00.007Z) and seq 1700000000000. A plain
SELECT * FROM N on the restored database still prints {"seq":7,"ts":"2023-11-14 22:13:20","v":42.5},
because the SQL read applies the mirror-image error - which is exactly why this would be found months later.

Suggested fix

Make the two JSONL sites speak the engine's layout, since that is the one the rows arrive in:

  • exporter: keep writing row[i] (it is already the engine layout) but say so, and have the importer read it
    as such; or, better, emit the sample in the SCHEMA order the javadoc claims by permuting on the way out.
  • importer: the timestamp is sample.get(0) and the value columns are sample.get(1..n) in non-timestamp
    schema order - i.e. drop timestampIdx from the sample indexing entirely, exactly as
    ObjectColumnsRowSource.kindsOf and PromQLEvaluator.findNonTsRowIndex already index.
    Either way the two ends must agree, and a mixed-vintage export needs a discriminator: today's export of a
    timestamp-first type is byte-identical under both readings, so the fix can be applied without a format
    version bump only if the exporter keeps emitting timestamp-first.
  • FetchFromTimeSeriesStep.next(): map by role, not by index - row[0] for the TIMESTAMP column and
    row[1 + nonTsIdx] for the rest, the way PromQLEvaluator does.
    A regression test that declares the timestamp anywhere but first - which the grammar now permits - would have
    caught all three.

Scope / confidence

Tried to refute it by: (a) checking whether a non-first TIMESTAMP is actually constructible - it is, through
the grammar (tsTypeMember is a repeatable list and CreateTimeSeriesTypeStatement inserts the column at
timestampPosition), through TimeSeriesTypeBuilder.withTag(...).withTimestamp(...), and through
withColumn which the JSONL restore itself uses; (b) checking whether the sealed layer uses a different
layout that would make the exporter right for some rows - it does not, TimeSeriesSealedStore also writes
row[0] = ts; (c) checking whether the INSERT path is symmetrically wrong so the two cancel at rest - it is
not, SaveElementStep.saveToTimeSeries resolves every column by name; (d) checking whether some validation
refuses a non-first timestamp on the export or import path - JsonlImporterFormat.createTimeSeriesType
checks the column NAMES and their order and passes here, since the order is faithfully preserved; (e)
running the whole thing. Falsified only if a non-first TIMESTAMP declaration is meant to be refused
somewhere, in which case the grammar comment for #7702 says the opposite.


Activity

  1. added
    backup-restore
    engine
    importer
    timeseries
    on Sep 18, 2026
  2. added this to the 26.10.1 milestone on Sep 18, 2026
  3. self-assigned this
    on Sep 18, 2026
  4. added
    severity:critical
    in progress
    on Sep 19, 2026
  5. added a commit that references this issue on Sep 22, 2026
  6. robfrank commented on Sep 22, 2026

    @robfrank
    Collaborator

    Fixed in #8141.

    An engine row is [timestamp, non-TIMESTAMP columns in schema order...] whatever position the TIMESTAMP column occupies in the declaration - TimeSeriesBucket.readRow writes position 0 from the row's own timestamp slot and then walks the schema skipping that column. Four consumers instead mapped row position i onto getTsColumns().get(i), which is only the same thing while TIMESTAMP is declared first, and #7702 made a later position spellable in CREATE TIMESERIES TYPE.

    Taking your findings in order:

    1. JsonlExporterFormat.exportTimeSeries's javadoc described the opposite of what it writes - fixed (documentation only; the bytes were always right).
    2. JsonlImporterFormat.loadTimeSeriesSamples read the sample by the TIMESTAMP column's schema position, so a restore either died with a bare ClassCastException or silently swapped the timestamp with the numeric column ahead of it - fixed.
    3. FetchFromTimeSeriesStep.next() mapped row[i] onto columns.get(i), so SELECT * returned a tag's value under the timestamp's name - fixed.
    4. One you did not report: TimeSeriesGateway.selectedColumns(columns, null) answered the raw schema, contradicting its own javadoc - fixed, and that single change covers six wire call sites at once (GET /ts/{db}/latest, POST /ts/{db}/query, the Grafana raw frame and both gRPC time-series RPCs), plus the Prometheus remote read's labels, series key and sample value.

    No format-version bump is needed: the exporter always emitted the engine layout, so existing files are already correct. 11 new regression tests across three modules pin the round trip in both its loud and silent shapes.

    Still open


    ❤️ Thanks for helping make ArcadeDB better! ArcadeDB is free and open source, sustained by its community. If it's useful to you or your company, please consider becoming a sponsor to keep development going.

  7. removed
    in progress
    on Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

backup-restorebugengineimporterseverity:criticaltimeseries

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions