Skip to content

Filter datapoint exports with literals so TimescaleDB can exclude chunks - #3674

Open
costajohnt wants to merge 1 commit into
openremote:mainfrom
costajohnt:fix/export-chunk-exclusion
Open

costajohnt wants to merge 1 commit into
openremote:mainfrom
costajohnt:fix/export-chunk-exclusion

Conversation

@costajohnt

@costajohnt costajohnt commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Description

Closes #3661

The datapoint export streams a COPY (...) TO STDOUT query. Since #2882 that query took its time bounds from tmp_export_bounds (cross join) and its (entity_id, attribute_name) pairs from tmp_export_attributes (join). Neither is known at plan time, so TimescaleDB could not exclude chunks or filter compressed batches: every export, even 1 hour of one attribute, scanned and decompressed the whole asset_datapoint hypertable.

What changed

AssetDatapointService:

  • New buildExportFilter builds the asset_datapoint filter with literals: ad.timestamp >= TIMESTAMP '...' and ad.timestamp <= TIMESTAMP '...' and (ad.entity_id, ad.attribute_name) in ((E'...', E'...'), ...). All three formats (CSV, CSV_CROSSTAB, CSV_CROSSTAB_MINUTE) use it.
  • tmp_export_bounds is removed.
  • tmp_export_attributes is only created for the crosstab formats, where it still provides the category query (column order) and maps each attribute to its generated col_N key. It no longer acts as the filter; the literal filter above restricts asset_datapoint before the join.
  • The crosstab inner query and category query are now written as plain SQL and passed to crosstab(...) through the same literal function, instead of hand-doubled quotes (''1 minute'').
  • A plain CSV export that lists the same attribute twice used to emit each row twice and now emits it once.
  • canQueryDatapoints (the count query run before every export) is unchanged: it already uses bind parameters, and EXPLAIN shows it gets chunk exclusion with both custom and generic plans (see below).

The UI timeout, the retry pileup and cancelling the COPY on client disconnect from the issue are not part of this PR.

How injection safety is ensured

COPY cannot take bind parameters, so values go into the SQL text. Every value goes through one of two functions:

  • toSqlTimestampLiteral(long): the bound is a long converted with the same JVM-local conversion as before (toDatapointLocalDateTime) and formatted with a fixed DateTimeFormatter (yyyy-MM-dd HH:mm:ss.SSS, plus BC for years before 1). The output only contains digits, -, :, ., space and BC; there is no user-controlled text in it.
  • toSqlStringLiteral(String): returns an escape string constant E'...' with every \ doubled and every ' doubled.
    • In an E'...' constant a backslash is always an escape character, so the result evaluates to exactly the input whatever standard_conforming_strings is set to. A plain '...' literal would not have that property when standard_conforming_strings = off.
    • Since the function is exact, it composes: the crosstab inner query (which contains E'...' literals) is itself passed through it, so the double escaping needed there is handled by applying the same function twice, not by hand.
    • NUL is rejected (IllegalArgumentException), as PostgreSQL text cannot hold it.
    • pgjdbc 42.7.13 sets client_encoding=UTF8 at startup and closes the connection if it changes, unless allowEncodingChanges is set (not set anywhere in this repo). In UTF-8 no multibyte character contains the byte of ' or \, so multibyte tricks against the escaping do not apply.
    • pgjdbc sends the COPY SQL as one simple Query message without JDBC escape processing (QueryExecutorImpl.startCopy).
  • Asset IDs are still validated with validateAssetId (^[0-9A-Za-z]{22}$) before they are quoted.

Tests

New features in AssetDatapointExportTest:

  • Export output is unchanged for plain and crosstab formats: two attributes with datapoints at known timestamps (plus out of range points), exact expected lines for all three formats. This feature was run against the unchanged code first and passed, so the expected lines are the pre-change output.
  • Export query filters with literals so TimescaleDB excludes chunks outside the range: datapoints spread over 40 days (several chunks) before a fixed anchor, Monday 2020-01-06 12:00, so the exported hour (11:00 to 12:00) can never span a chunk boundary (chunk intervals are whole days and start at midnight); for that 1 hour, one attribute export it asserts the filter and the COPY query carry TIMESTAMP '...' bounds and the (entity_id, attribute_name) in ((E'...', E'...')) filter, contain no tmp_export, that EXPLAIN only references one chunk, and that the filter returns only the datapoint in that hour.
  • Export SQL literals keep quotes and backslashes inside the literal: with standard_conforming_strings both off and on, every test string (an attribute name with ', \', \\, '' and a trailing \, plus five names that try to close the literal with ', \' and \'') round-trips exactly through select <literal> and through a nested literal. An attribute with that name exports correctly in all three formats, and the breakout names export only a header in all three formats.

Commands (local, fresh test stack from profile/dev-testing.yml brought up before and down after, JDK 21, -Dorg.gradle.jvmargs=-Xmx4g --max-workers=4; the last two lines are the run on the final commit):

./gradlew --no-scan --no-configuration-cache :test:test --tests '*AssetDatapointExportTest.Export output is unchanged*'   # on the unchanged code: 1 passed
./gradlew --no-scan --no-configuration-cache spotlessJavaCheck spotlessGroovyCheck                                          # passed
./gradlew --no-scan --no-configuration-cache :test:test --tests 'org.openremote.test.assets.AssetDatapointExportTest'      # with the change: 9 passed, 0 failed, 0 skipped

EXPLAIN before and after

Local test DB, 3 attributes with one datapoint per minute over 40 days (7 chunks, all but the newest compressed), exporting 1 hour of one attribute 3 days ago (60 rows), EXPLAIN (ANALYZE, BUFFERS):

Before (temp table filters) After (literal filters)
Chunks scanned 7 (all) 1
Rows read from asset_datapoint 172,804 1,000 (one compressed batch)
Shared buffers 1,178 36
Execution time 69.0 ms 0.32 ms

After, the compressed chunk is filtered on entity_id, attribute_name and the batch min/max timestamps before decompression. The issue has the production-sized numbers (126 chunks, about 104 s before vs 0.17 ms after).

Count query from canQueryDatapoints (bind parameters, unchanged) on the same data: custom plan scans 1 chunk; with plan_cache_mode = force_generic_plan the plan shows Chunks excluded during startup: 6 and scans 1 chunk.

Downstream

doExportDatapoints keeps its signature. buildCopyToStdoutQuery was private and is now protected with a new signature, and ExportColumn is now protected; nothing outside this class could use either before. No Extensions, Custom Project or documentation change is needed. I did not build Extensions against this change.

Checklist

  • 1. Acceptance criteria of the linked issue(s) are met
  • 2. Tests are written and all tests pass
  • 3. Changes are manually tested by you and the reviewer
  • 4. Documentation is written or updated

The export COPY query read its time bounds and attribute pairs from temp
tables, so TimescaleDB could neither exclude chunks nor filter compressed
batches and every export scanned the whole asset_datapoint hypertable.

Build the filter from literals instead: timestamps formatted from the
typed bounds, asset IDs validated, and strings as E'' constants with
quotes and backslashes doubled, which evaluate to the input whatever
standard_conforming_strings is and nest safely in the crosstab query
text. tmp_export_bounds is gone; tmp_export_attributes is only created
for the crosstab formats, for column order and keys.

Closes openremote#3661
@sonarqubecloud

sonarqubecloud Bot commented Dec 5, 2026

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Datapoint export scans the whole asset_datapoint hypertable and times out for any range

1 participant