Repository navigation
Optionally store time series data in a TimescaleDB hypertable - #2909
Ahmad-Wahid wants to merge 8 commits into
Conversation
…rtable `flexmeasures db-ops enable-timescaledb` converts the timed_belief table into a TimescaleDB hypertable, partitioned into chunks on event_start (--chunk-time-interval, 7 days by default). With --compress-after, it also compresses chunks older than that, segmented per sensor and data source, and adds a policy to keep doing so. This is an explicit command rather than a migration: TimescaleDB's Docker images install the extension into every new database, so its presence says nothing about whether a host chose it, and converting a populated table blocks writes until all rows have moved into chunks. The hypertable keeps FlexMeasures' own indexes and skips TimescaleDB's default one, so that `flexmeasures db migrate` does not propose dropping an index the data model does not declare. The trigger that records which sources have data on which sensors keeps working on the hypertable, including for compressed chunks. On 7 million beliefs, compression shrank the table and its indexes from 1.6 GB to 115 MB, while single-sensor queries stayed equally fast. Signed-off-by: Ahmad-Wahid <ahmedwahid16101@gmail.com>
Explain what to expect from storing time series data in TimescaleDB (much less storage, similar query times while data fits in memory, slower queries without a time range, slower writes to compressed data), and what to check before converting (writes are blocked while converting, there is no way back without a dump and restore, CONCURRENTLY-built indexes, managed hosting support and telemetry). Signed-off-by: Ahmad-Wahid <ahmedwahid16101@gmail.com>
Documentation build overview
11 files changed ·
|
Catalog lookups are select()s over lightweight table definitions, and TimescaleDB's functions (create_hypertable, add_compression_policy, show_chunks, compress_chunk and the size functions) are func expressions, with timed_belief taken from the TimedBelief model rather than spelled out. The three statements SQLAlchemy has no construct for (CREATE EXTENSION, ANALYZE and the compression settings) are DDL elements bound to the TimedBelief table, so SQLAlchemy quotes its name. SQLAlchemy cannot pass PostgreSQL's named arguments, so create_hypertable's flags now go by position. The test therefore also checks that converting adds no index the data model does not declare, which fails if create_default_indexes is passed in the wrong position. Signed-off-by: Ahmad-Wahid <ahmedwahid16101@gmail.com>
Flix6x
left a comment
There was a problem hiding this comment.
Thanks @Ahmad-Wahid, this is a careful, opt-in first step for #601: SQLAlchemy throughout, the intervals as bound parameters, one transaction that rolls back cleanly (also the CREATE EXTENSION when you answer no), and only FlexMeasures' own indexes on the hypertable, so flexmeasures db check lists exactly the same operations before and after converting. It is still a draft, but I am requesting changes so the points below are settled before it can be merged. I tried it on the timescale/timescaledb:2.22.1-pg17 image: live on a small database (173 thousand beliefs), and in a benchmark on 2.24 million beliefs with the server capped at 192 MB, page cache included, so the table (533 MiB) really did not fit in memory.
Bugs and requested changes
-
The version floor is too low.
MINIMUM_VERSION = (2, 13), but thesensor_data_sourcetrigger uses a transition table (REFERENCING NEW TABLE), which hypertables only accept from TimescaleDB 2.18. On 2.17.2 the conversion fails with "hypertables do not support transition tables in triggers" (rolled back, fine). 2.18.0 up to 2.22.1 all work. Please make it 2.18, in the docs too, with the trigger as the reason. -
Re-running with another
--compress-afterdoes not change the policy.add_compression_policy(..., if_not_exists => true)keeps the existing policy: after--compress-after "30 days", a run with"60 days"compresses by 60 days now, but the policy job still says 30 days. The docs say "run the command again to add or change compression". Removing the policy first (remove_compression_policy(..., if_exists => true)), oralter_jobon its config, would make that true. -
The re-run count. A second run with the same options says "Compressed 21 chunk(s)" while it compressed nothing, because
compress_chunk(..., if_not_compressed => true)also returns chunks that were compressed already. Selecting only uncompressed chunks (timescaledb_information.chunks.is_compressed) gives the real count. -
--chunk-time-intervalon an existing hypertable is silently ignored. Either apply it to future chunks (set_chunk_time_interval) or say so. -
The documented way back loses the data. The docs say going back "takes a dump and restore of the time series data". A data-only dump with the options of
flexmeasures db-ops dumpholds the beliefs only in the chunk tables (48 here, the compressed ones in compressed form). Restored into a plain schema, 0 of 172,800 beliefs came back; the same dump of the plain database restores all of them. That line should point to the command of point 10 instead. Backups of a converted database also need TimescaleDB'stimescaledb_pre_restore()/timescaledb_post_restore()and the same extension version on the target, which the docs could mention. And the prompt could say that this cannot be undone with FlexMeasures, and that it compresses when--compress-afteris given. A run with--compress-afteron an existing hypertable asks nothing at all. -
Please use
--forceinstead of--yes. Elsewhere in FlexMeasures, skipping the confirmation prompt is--force/--no-force(all theflexmeasures deletecommands inflexmeasures/cli/data_delete.py); this would be the only command with--yes. -
Please don't offer converting without compressing. As measured below, a hypertable without compression was slower than the plain table on every read and no smaller: it only costs. Compression could be part of the conversion, with
--compress-afterdefaulting to something like 30 days. (On an Apache-only TimescaleDB, which cannot compress, the command could then simply refuse.) -
Not for play servers. Play servers (
FLEXMEASURES_MODE = "play") are for simulations, which write into past periods and rerun over them: late data and overwrites. Once those periods are compressed, that is the slow case measured below (overwrites 2.6 times slower), and deleting beliefs there costs a decompression too. Could the docs say the conversion suits live hosts with a long history, not play servers, and could the command warn (or ask for--force) in play mode?
Your open questions
- Migrations and CI. Migrations on a large table like
timed_beliefbuild or drop indexesCONCURRENTLY, so writes can go on meanwhile. TimescaleDB refuses that on a hypertable, as each chunk has its own copy of every index (dropping fails too, as the chunk indexes would go with it). So such a migration errors out on a converted database and stops halfway. Two migrations do that:d4a7c1e93b52(both ways) andb7e5a2c40f18(drop in the upgrade, create in the downgrade). On a converted database,flexmeasures db downgrade 3bc1e29ca1f4fails inb7e5a2c40f18's downgrade and stops there (upgrading back works); a converted database at an older revision cannot upgrade acrossd4a7c1e93b52. On a plain copy both directions work. Hosts on v1.2 are past both, so today this only affects downgrades, but the next online migration ontimed_beliefwould break converted hosts, and CI would not notice: on plain Postgres the conversion test is skipped (I checked: 1 passed, 1 skipped; on TimescaleDB both pass). So yes to a CI job on the TimescaleDB image, running this test and the migrations. Could the docs name the two migrations, and could this PR also add a small migration helper that leaves outCONCURRENTLYwhentimed_beliefis a hypertable (perhaps withWITH (timescaledb.transaction_per_chunk)instead)? Using it ind4a7c1e93b52andb7e5a2c40f18would make downgrades work too, and future migrations would have it at hand. - No way back. Please add the way back as a command too,
flexmeasures db-ops disable-timescaledb: copy the beliefs into a new plaintimed_belieftable on the same server (decompressing on the way), rebuild its primary key, indexes, foreign keys and thesensor_data_sourcetrigger, and swap. Before it starts, it should check the storage this needs (the decompressed size plus indexes, e.g. fromhypertable_compression_stats) and say so, or refuse without--forcewhen it may not fit. A test for it would fit in the TimescaleDB CI job of point 9.
Performance, measured larger than memory
Through TimedBelief.search and save_to_db, database time, median of 21 runs, every run asking for another sensor and period, caches dropped per round (plain / hypertable / compressed):
| Plain | Hypertable | Compressed | |
|---|---|---|---|
| 1 day, 1 meter | 5 ms | 24 ms | 21 ms |
| 1 month, 1 meter | 29 ms | 53 ms | 27 ms |
| 1 year, 1 meter, resampled to 1 hour | 221 ms | 346 ms | 183 ms |
| 1 day, 20 meters | 55 ms | 81 ms | 72 ms |
| 1 week of forecasts, most recent beliefs | 22 ms | 32 ms | 10 ms |
| Latest value, 1 meter (warm) | 41 ms | 83 ms | 149 ms |
| Late readings into a compressed period (1,920 beliefs) | 175 ms | 183 ms | 217 ms |
| Overwriting readings there (upsert) | 181 ms | 185 ms | 464 ms |
| Table plus indexes | 533 MiB | 538 MiB | 63 MiB |
So on an SSD, even when the table is three times larger than the server's memory, compression is about storage (8 times smaller here), not speed: some reads get faster, one-meter reads get slower, and writes into compressed chunks cost up to 2.6 times as much. A hypertable without compression was slower than the plain table on every one of these reads and no smaller. Could the PR description and the docs report this trade-off honestly, so hosts can weigh it: storage about 8 times smaller; reads mixed (a week of forecasts 2 times faster, one meter's day 4 times slower, the latest value 3.6 times slower); writes into compressed periods 1.2 (late data) to 2.6 times (overwrites) slower; and a conversion that takes minutes for a large host? That would replace "smaller data means more of it stays in memory" and "similar query times". Converting took 94 s for 2.24 million beliefs here (2 CPUs at low priority), compressing 14 s.
Smaller points
- Hosts on an Apache-only TimescaleDB: a first run with
--compress-afterfails cleanly. But a database compressed earlier and then served by an Apache-only edition (say, after moving to a managed service) still reads its compressed chunks, while writing into one fails with "functionality not supported under the current apache license". Worth a line in the docs. - Telemetry: the official image starts with
timescaledb.telemetry_level = basic. A one-line notice from the command when it is notoffwould reach hosts at the moment it matters. - The default chunk of 7 days gives about 260 chunks for five years of data, and queries without a time range are planned against all of them (latest value: 41 ms plain, 149 ms compressed, warm). The docs already say larger chunks help; maybe 30 days as the default?
- Tests that would have caught the points above: an upsert into a compressed chunk, a re-run with another
--compress-after, and the version floor. - The options are kebab-case, good (with
--forceas above).
…at they say From the review of enable-timescaledb: - Require TimescaleDB 2.18, the first version whose hypertables accept the transition table of the sensor_data_source trigger. - Compress as part of the conversion (after 30 days by default), and refuse on the Apache-licensed edition, which cannot compress: a hypertable without compression only costs. - Default to chunks of 30 days, to keep queries without a time range from being planned against hundreds of chunks. - On a hypertable already, replace the compression policy rather than keep the old one, apply --chunk-time-interval to new chunks rather than ignore it, and count only the chunks that were actually compressed. - Ask for confirmation whenever something changes, saying what will be compressed and that FlexMeasures cannot undo it. - Skip the prompt with --force/--no-force, as the other FlexMeasures commands do, instead of --yes. - Refuse on play servers unless forced, as simulations write into past (compressed) periods. - Warn when TimescaleDB sends telemetry. Signed-off-by: Ahmad-Wahid <ahmedwahid16101@gmail.com>
`flexmeasures db-ops disable-timescaledb` moves the hypertable into a schema of its own, creates a plain timed_belief from the data model in its place, copies the beliefs over (decompressing them on the way), adds the indexes, foreign keys and sensor_data_source trigger, and drops the hypertable, all in one transaction. Before it starts, it says how much disk space the copy needs. It refuses when the database is not migrated to the latest revision, as the table is created from the current data model. A data-only dump of a hypertable holds the beliefs in its chunk tables, so it cannot be restored into a plain schema: this replaces the dump and restore the docs suggested. Signed-off-by: Ahmad-Wahid <ahmedwahid16101@gmail.com>
TimescaleDB refuses to build or drop indexes CONCURRENTLY on a hypertable, so d4a7c1e93b52 (both ways) and b7e5a2c40f18 (its drops and its downgrade's creates) stopped halfway on a converted database. A new helper module, flexmeasures.data.migration_utils, leaves out CONCURRENTLY there, and builds new indexes one chunk at a time (timescaledb.transaction_per_chunk) instead. On a hypertable, d4a7c1e93b52 rebuilds the primary key in its transaction, as TimescaleDB builds unique indexes neither concurrently nor per chunk, and does not adopt an existing index as a primary key. Plain tables keep the online path. Signed-off-by: Ahmad-Wahid <ahmedwahid16101@gmail.com>
The test job runs plain PostgreSQL, which skips the TimescaleDB tests. A new job runs them on the TimescaleDB image, at 2.18.0 (the lowest version supported) and at 2.22.1, and runs the migrations down past d4a7c1e93b52 and b7e5a2c40f18 and up again on a compressed hypertable, before going back to a plain table and checking that no belief got lost. Signed-off-by: Ahmad-Wahid <ahmedwahid16101@gmail.com>
…d the way back Report what compression costs as well as what it saves (storage 8 times smaller, reads mixed, writes into compressed periods up to 2.6 times slower), say it suits live hosts with a long history rather than play servers, and document the 2.18 version floor, backups of a converted database, the migration helpers, the Apache-licensed edition, changing the settings later, and disable-timescaledb. Signed-off-by: Ahmad-Wahid <ahmedwahid16101@gmail.com>
|
Thanks @Flix6x, for the careful review and for measuring larger than memory. I addressed every point in five new commits:
Performance: the PR description and docs now report your measurements and the trade-off as you put it, in place of "similar query times". Smaller points: the Apache-edition caveat for compressed databases is in the docs, the command warns when telemetry is on, chunks now default to 30 days, and the tests now cover an upsert into a compressed chunk, a re-run with another One question for you: on a hypertable, |
Description
FlexMeasures keeps all time series data in one table,
timed_belief. This PR lets hosts whose PostgreSQL server provides TimescaleDB (2.18 or later) store that table as a compressed TimescaleDB hypertable, and go back to a plain table. It is fully optional: FlexMeasures keeps working on plain PostgreSQL, and its queries don't change.flexmeasures db-ops enable-timescaledb, which convertstimed_beliefinto a hypertable partitioned into chunks onevent_start(--chunk-time-interval, 30 days by default), and compresses chunks whose events are older than--compress-after(30 days by default), segmented per sensor and data source, with a policy to keep doing so.--compress-after) or sets the chunk time interval for new chunks (--chunk-time-interval), and reports how many chunks it actually compressed.--force, as in theflexmeasures deletecommands), saying what will be compressed and how to go back.FLEXMEASURES_MODE = "play") unless forced, as simulations write into past periods, which is the slow case of compressed data.flexmeasures db-ops disable-timescaledb, which copies the beliefs into a new plaintimed_belieftable (decompressing them on the way), rebuilds its primary key, indexes, foreign keys andsensor_data_sourcetrigger, and drops the hypertable, in one transaction. It first says how much disk space the copy needs, and refuses when the database is not migrated to the latest revision, as the table is created from the current data model.sensor_data_sourcetrigger only from then on.event_start, so thatflexmeasures db migratenever proposes dropping an index the data model doesn't declare.flexmeasures/data/services/timescaledb.py, with queries and TimescaleDB function calls built with SQLAlchemy.CREATE/DROP INDEX CONCURRENTLYon a hypertable, sod4a7c1e93b52andb7e5a2c40f18stopped halfway on a converted database. A new helper module,flexmeasures/data/migration_utils.py, leaves outCONCURRENTLYon a hypertable (building new indexes per chunk withtimescaledb.transaction_per_chunk), and both migrations use it. On a hypertable,d4a7c1e93b52rebuilds the primary key in its transaction, as TimescaleDB builds unique indexes neither concurrently nor per chunk, nor adopts an existing index as a primary key. Plain tables keep the online path.timescale/timescaledb2.18.0 and 2.22.1, and runs the migrations down past both migrations and up again on a compressed hypertable, then goes back to a plain table and checks that no belief got lost.host/data.rst).documentation/changelog.rst(and in the CLI changelog)Why a command and not a migration
TimescaleDB's own Docker images install the extension into every new database, so the extension being present says nothing about whether a host chose TimescaleDB. A migration keyed on it would convert the table, and block writes to it, during a routine
flexmeasures db upgrade.What it does and doesn't speed up
Measured by @Flix6x on 2.24 million beliefs, with the server capped at 192 MB (page cache included), so that the table really did not fit in memory. Through
TimedBelief.searchandsave_to_db, database time, median of 21 runs, caches dropped per round:So compression is about storage, not speed:
This suits live hosts with a long history, where storage is the concern, and not play servers.
Open questions for reviewers
d4a7c1e93b52rebuilds the primary key under a lock that blocks reads and writes until every chunk is done. Hosts on v1.2 are past it, so this only matters for downgrades. Is that acceptable?disable-timescaledbcannot see the free disk space on the database server, so it states the space the copy needs and asks for confirmation (unless--force), rather than checking whether it fits.Look & Feel
How to test
pytest flexmeasures/cli/tests/test_db_ops_fresh_db.py--force) and on the Apache-licensed edition, it refuses without converting.test_enable_timescaledbconverts and compresses, checks that search results are unchanged, re-runs with the same and another--compress-afterand another--chunk-time-interval, then writes a late belief and an overwrite (upsert) into compressed chunks, and checks that thesensor_data_sourcetrigger records the late one.test_disable_timescaledbgoes back and checks the beliefs, primary key, indexes, foreign keys and trigger.--chunk-time-interval, a 2.13 floor, no play-server or Apache check, and a way back without indexes, foreign keys or trigger.