Skip to content

Clickhouse backup - #520

Open
aagbsn wants to merge 47 commits into
mainfrom
clickhouse-backup
Open

aagbsn wants to merge 47 commits into
mainfrom
clickhouse-backup

Conversation

@aagbsn

@aagbsn aagbsn commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

backup scripts and alerting for backing up to S3 compatible storage. Tests in harness for backup and restore with full and incremental snapshots; adds alerting for failed jobs and missing (e.g. new) tables.

aagbsn added 27 commits October 20, 2026 14:28
Nothing backed up the production cluster: the weekly ooni-db-backup export
reads a legacy local ClickHouse (its fastpath files have been empty since
mid-2025), and scripts/dump-tables-ch.sh listed tables that no longer
exist while missing obs_*, analysis_web_measurement and others.

Add a clickhouse_backup role that runs ClickHouse's native BACKUP daily
from a systemd timer. Each table has its own chain: a full backup every
30 days and incrementals in between, so a failure in obs_web (3.9 TB)
doesn't cost the other tables their backup. The two newest complete
chains are kept; chains pinned with --keep (e.g. before an upgrade step)
are kept until released.

A host runs the jobs set in its host_vars, one per bucket:
- data3, "measurements": the replicated tables, minus the private ones
  and data1's. data3 isn't behind clickhouseproxy and doesn't run Airflow.
- data3, "private": msmt_feedback, faulty_measurements, url_priorities,
  in their own bucket, since R2 tokens grant access per bucket.
- data1, "data1": the plain MergeTree tables whose data only data1 holds
  (labeling_frames, event_detector_cusums, event_detector_v2_changepoints,
  changepoint_label). Remove a table from clickhouse_backup_data1_tables
  once it's replicated and data3 picks it up.

The R2 endpoint and token come from SSM. R2 rejects multipart uploads
whose parts (all but the last) differ in size, so the uploads use fixed
128 MiB parts (s3_upload_part_size_multiply_factor = 1). With R2's
10,000-part limit a file can reach 1.25 TiB; the largest file of a backup
is one column of one part, and parts stop growing at 150 GB.

After each table the script writes its result to a node_exporter textfile
(ooni_clickhouse_backup_*), and prometheus_node_exporter gets a
node_exporter_textfile_dir option for it. New alerts: a table's backup
failed, no backup of a table for 3 days, no results from data1 or data3
for a day, and data3's load over half its CPUs for 15 minutes. TextfileJam
skips the backup file, which changes daily rather than hourly.

Things found while testing against 24.8.6.70 and MinIO:
- BACKUP saves only the schema of EmbeddedRocksDB and Join tables, so
  their rows are exported in Native format alongside the backup.
- An incremental backup stores its base_backup argument, keys included,
  in its .backup file. ClickHouse gets the bucket keys from <s3>
  endpoints in config.d instead, which it reloads without a restart.
- max_backup_bandwidth is a query setting (BACKUP ... SETTINGS rejects
  it), and actual throughput is about a third of the value.
- A 24.8 server segfaults restoring a backup taken on 26.8, so the
  runbook pins a backup before each upgrade step.

Remove the outdated dump and restore scripts.
A table started a new chain once its chain was 30 days old, counted
from when its full began. With weekly runs that gives a full every 5
weeks, and a threshold of 28 days would slip a week whenever a table's
backup started a few minutes earlier than it did in the full.

A table now starts a new chain at its first backup in each calendar
month (UTC): the 1st with daily runs, the first Sunday with weekly
ones. A full that fails is retried at the next run, as the latest
complete chain is still from the month before.
clickhouse_backup_full_interval_days is gone.
Requires= in the timer unit started ooni-clickhouse-backup.service
whenever the timer started: at every boot of data1 and data3, and on
every deploy that restarts the timer. Backups now start only at
OnCalendar; Persistent=true still runs one missed while the host was
down.
The alerts only said when something went wrong. At the end of a run
the script now records each job's result (ooni_clickhouse_backup_last_
run_*: when it finished, how long it took, tables backed up, in full,
and failed), and ClickHouseBackupCompleted fires for an hour after a
run with no failed table.

It goes to a new Alertmanager receiver, slack-notice: one message per
job run in #ooni-bots, without the [FIRING] prefix, a "resolved"
message or email. ClickHouseBackupFailed now says that nothing was
deleted and that the next run retries the table.
"1 tables backed up, 1 of them in full" now reads "Tables backed up: 1,
in full: 1".
… it changes

tests/run.sh renders the role's configs from its templates, and
Alertmanager's from its role, with Ansible, then:
- promtool unit-tests the backup alerts in alert_rules.yml, and amtool
  checks Alertmanager's config and that the alerts reach the right
  receivers;
- test_schedule.py checks when full backups start and what is pruned,
  over months of daily and weekly runs with failures;
- test_e2e.py runs the script against ClickHouse 24.8.6.70, MinIO for
  R2, node_exporter, Prometheus 2.42.0 and Alertmanager 0.25.0 (the
  versions in production) and a stand-in for Slack, in docker compose:
  full and incremental backups and a restore; a failed run; a month's
  new full interrupted by a ClickHouse restart, which deletes nothing,
  then completed with the oldest chain pruned; and the Slack messages
  and emails each causes.

The workflow runs it on pull requests and pushes to main that change
this role, the alert rules or Alertmanager's role. About 7 minutes.
The script now runs on Debian bookworm with its python3 and
python3-boto3, the packages the role installs on the ClickHouse hosts,
instead of a Python image with boto3 from pip. The workflow installs
ansible-core and python3-boto3 with apt for the scripts around it.
…ured

max_backup_bandwidth was 120 MB/s, on the strength of 24.8 uploading at
about a third of it in tests against MinIO. If production doesn't show
the same, that would take most of the nodes' 1 Gbit/s link. Cap it at
50 MB/s, about 31 hours for a full backup of everything, and raise it
if the first backups show the third: about 4 days for a full, longer
than ClickHouseBackupStale's 3. The comments and the runbook say how to
check the rate.
counters_test_list is detached permanently, so it's no longer in
system.tables, which the script takes its tables from.
The runbook listed fingerprints_* and session_expunge among the tables
whose rows each backup exports, but neither is backed up: the
fingerprints tables are only on data1 and data2 and the hourly updater
rebuilds them, and session_expunge is empty on both. Only test_groups,
on data3, is exported.
The experiment table on data2 is gone, and data2 isn't backed up anyway.
The listing is the command's output, for stdout and pipes; log is for
what run and release report, to stderr and the journal.
A full backup of everything takes more than a day, so run weekly
instead of daily for now: incrementals every Sunday at 02:30 UTC, each
on top of the one before, and a new full on the first Sunday of each
month. The timer's first run after a deploy is then the next Sunday;
the runbook says how to start the first full on deploy day.
…upStale

With weekly runs a table's last backup is normally up to a week old, so
ClickHouseBackupStale fired after 3 days would fire every week. It now
fires after 8 days, and not while the table's job is still running: on
the first Sunday of a month the fulls take more than a day, and the
largest tables come last. The promtool tests cover both.
…run on the host

The alert was held back only while the table's own job ran. On data3 the
jobs run one after the other, so on the first Sunday of a month private
waited more than a day behind measurements' full backups and passed 8
days without one, while nothing was wrong. And a run killed without
reaching its finally left running at 1, which held the alert back for
good.

The script now also exports, per job, when its current run started
(ooni_clickhouse_backup_running_since_timestamp_seconds, 0 when idle).
The alert is held back while any job on the host is in a run that
started in the last 5 days. The promtool tests cover a 7- and a 9-day
old table with nothing running, a job waiting behind another job's run,
and a stuck run; test_job.py the new metric and older state files.
…tables

The other jobs ran with no tables, recorded a completed run of 0 tables
(ClickHouseBackupCompleted posted it to Slack) and overwrote their real
weekly results.
At boot, Persistent=true catches up a missed Sunday before ClickHouse
accepts queries. The checks before the table loop then failed outside
any try: the run died with a traceback, skipped the later jobs and
wrote no metrics, and nothing alerted until ClickHouseBackupStale 8
days later. A run now waits up to 10 minutes for ClickHouse
(clickhouse_wait_seconds). If it still can't start, the job's tables
are marked failed, so ClickHouseBackupFailed says so, and the next job
runs.

One failed status poll also gave up on a backup that can run for days,
while the BACKUP carried on server-side. Polls are now retried for up to
10 minutes.
A host has no backup results until its first run, which with weekly
runs can be up to a week after the role is deployed: the 26 h wait
alerted every 3 hours until then.
…restore test_groups

Before upgrading, step 4 re-enabled the timer first, which with
Persistent=true may start a run for a missed Sunday, then ran a
multi-day run --full in a shell. Run it with systemd-run while the
timer is still disabled, and re-enable the timer afterwards. Note that
ClickHouse waits for running backups when it stops
(shutdown_wait_backups_and_restores, TimeoutStopSec=infinity), so a
restart during a full hangs until it is done.

The restore example loaded fingerprints_dns, which isn't backed up;
test_groups is the table it's for.
…, test the backup host alert

node_exporter's file label is the file's full path, so the anchored
"ooni_clickhouse_backup.*" never matched (TextfileJam matches nothing
today anyway: it uses node_exporter's pre-0.16 metric names). The
promtool tests now cover the exclusion, and
ClickHouseBackupHostLoadHigh, whose description no longer assumes a
backup is the cause.
An empty include_tables meant every table. data1's job includes only
clickhouse_backup_data1_tables, which is to be emptied as its tables
become replicated; data1 would then have backed up every table,
private ones included, into the measurements bucket, under the same
prefixes as data3, whose in-progress full it could also have removed
as incomplete. "*" now selects every table and an empty list none, with
a warning; data3's measurements job and the role's default job say
["*"].
…cked up

The state file kept every table and job it had ever seen, so a table
dropped, or moved to another job (as data1's tables will be once
replicated), kept its old results and alerted forever:
ClickHouseBackupStale after 8 days, or ClickHouseBackupFailed. After a
run without --table, a job now forgets the tables it no longer selects,
and every run forgets the jobs no longer in the config.
…letes, fsync state

- running_backups() matched the endpoint by substring, so the
  measurements bucket also matched the private bucket's backups; match
  <bucket>/<prefix>/.
- delete_objects reports keys it didn't delete in a 200 response, which
  were ignored; raise on them.
- Fsync the state and metrics files before they replace the old ones,
  and start from no results if the state file is unreadable instead of
  failing every command.
- Pass the upload settings to the EmbeddedRocksDB/Join export too: R2
  needs its multipart parts to be the same size.
…utput and logs on failure

ClickHouse waits for running backups when it stops
(shutdown_wait_backups_and_restores), so the interrupted-full scenario
only worked because compose restart killed it after 10 s; kill it
instead. Failing run checks now show what the script said, run.sh
prints the containers' logs when the test fails and removes containers
left by KEEP=1 before starting, and the unit tests silence the
script's log.
…ocksDB rows, and the new full after pruning

Only the newest incremental was restored. Two more runs now give
fastpath a full and two incrementals, and each of the three restores
fastpath as it was at that backup (200,000, 201,000 and 202,000 rows,
by count and a checksum of every row). fingerprints_dns, an
EmbeddedRocksDB table, is restored as the runbook says: RESTORE its
schema, then load data.native.zst. After the interrupted full and the
pruning, the new full restores obs_web. The run takes about 9 minutes.
…vers

A table created on data1 or data2 only, like data1's own tables were,
was in no backup and nothing said so: data3 doesn't have it, and data1's
job lists its tables. After each run, data3 now lists the tables on
every node (clickhouse_backup_check_cluster: oonidata_cluster) and
reports those that no job here backs up (from a table on this host),
that aren't in clickhouse_backup_data1_tables (backed up by data1) and
that aren't excluded, as ooni_clickhouse_backup_table_not_backed_up.
ClickHouseTableNotBackedUp names the table and its nodes and says how to
fix it.

clickhouse_backup_exclude_tables becomes the list of tables that are
never backed up, each with its reason: fingerprints_dns and
fingerprints_http (the hourly updater rebuilds them) and session_expunge
(empty, unused) join it. That changes no backup: they're not on data3,
and data1's job lists its tables. The end-to-end test's EmbeddedRocksDB
table is now test_groups, as in production.
…that no backup covers

The test environment gets a second ClickHouse node, data1, with data3 in
one test cluster. A new step creates a table on data1 only and checks
that ClickHouseTableNotBackedUp names it in Slack, and no other table
(labeling_frames is data1's, asnmeta_tmp is excluded). It comes after
the Completed step, whose check that nothing went to email it would
otherwise break.
@aagbsn
aagbsn marked this pull request as draft October 22, 2026 15:12
Comment thread ansible/group_vars/clickhouse/vars.yml Resolved
Comment thread ansible/group_vars/clickhouse/vars.yml Resolved
While a materialized view exists without its target table, every insert
into the view's source table fails: for counters_asn_test_list, fastpath's
inserts. Tested on 24.8. It matters once #521's follow-up gives
counters_asn_test_list an explicit target table.
@aagbsn aagbsn mentioned this pull request Oct 23, 2026
With the default of 20 in-flight parts per file, disk seek on data3
caused so much degredation uploads timed out and nothing finished.
Set s3_max_inflight_parts_for_one_file to 1, and raise
max_backup_bandwidth to 100 MB/s.
@aagbsn aagbsn mentioned this pull request Oct 28, 2026
@aagbsn
aagbsn marked this pull request as ready for review October 28, 2026 10:01
self.fulls(7), ["2026-10-23", "2026-11-01", "2026-12-06", "2027-01-03", "2027-02-07", "2027-03-07"]
)

def test_daily_fulls_on_the_first_of_each_month(self):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these tests verify a schedule that uses daily incrementals and weekly full backups - there's some large unpartitioned tables so it is likely that a daily incremental would also write a significant delta - the schedule was revised to monthly full backups and weekly incrementals because of this. In the worst case, this means about 7 days of data needs to be rebuilt. What might be confusing to a reviewer is the test names reflect a weekly full and daily incremental backup schedule.

@ai-13rac1

Copy link
Copy Markdown

An Opus 5.5 review as requested by @aagbsn

Review of ooni/devops PR 520 (ClickHouse backups to Cloudflare R2)

The design holds up, but I'd fix two things before the first production run. Any new or unlisted table goes to the bucket meant to be shareable with researchers, so personal data could land there. And one R2 key that can delete every backup sits on the database hosts, where ClickHouse also lets queries use it implicitly. Beyond those, a few operational risks are worth fixing before the first monthly full.

I reviewed all 34 commits (about 2,450 lines across 35 files). I checked table schemas against ooni/backend, but didn't run the container tests.

What's solid: keys never appear in BACKUP queries; R2's equal-part-size rule is handled; delete_objects errors are checked; the metrics file is written atomically; each table has its own backup chain; a backup left running by a killed run is detected before starting a new one. The e2e tests restore every chain and kill ClickHouse mid-backup, which is a strong suite.

High

  1. New tables default to the shareable bucket. data3's measurements job uses include_tables: ["*"] (host_vars/data3…:10), and only three tables are listed as private. Anything not on that list goes to ooni-clickhouse-backup, the bucket the runbook says researchers may get read access to.

    • The legacy schema has accounts (account ids), incidents (email_address, creator_account_id) and oonirun (author, an email). All three were in the old dump-tables-ch.sh this PR deletes.
    • Check whether any of them, or anything similar, exists in the ooni database.
    • Fix: list the measurement tables explicitly. An unclassified table then fires ClickHouseTableNotBackedUp and has to be classified, instead of going to the shared bucket.
  2. One credential can wipe both buckets, and ClickHouse hands it out. The R2 token has Object Read & Write on both buckets and lives on data1 and data3, so a bug in pruning, a mistyped prefix or a compromised host can delete every backup. There's no immutable copy.

    • Because the keys are in the <s3> endpoint config, ClickHouse uses them for any query whose URL falls under that endpoint. Any ClickHouse user allowed to run s3() can therefore read the private bucket (msmt_feedback's account ids) or overwrite backups.
    • Fixes:
      • add R2 bucket lock or retention rules at least as long as the pruning age;
      • check which ClickHouse users hold the S3 source grant;
      • consider a dedicated backup user rather than the admin user.

Medium

  1. The credentials file is installed without a reload. The template comment says ClickHouse "reloads this file without a restart" (ooni_backup_s3.xml.j2:6). The last commit's message says SYSTEM RELOAD CONFIG didn't work, and the runbook now says to use systemctl reload clickhouse-server. The role has no handler for this, so on first deploy or key rotation ClickHouse can keep the old (or no) credentials and the backup fails. Add a handler and fix the template comment.

  2. Restarting ClickHouse during a full hangs for a day or more. The runbook notes that shutdown_wait_backups_and_restores makes ClickHouse wait for running backups when it stops. Any ClickHouse restart on data3 during the monthly full (an Ansible restart handler, an apt upgrade, a reboot) blocks until the backup finishes. Consider setting it to false: an interrupted backup is then cleaned up and retried, which the tests already cover. At least add a check to the ClickHouse role.

  3. Network capacity. 100 MB/s is about 800 Mbit/s, and data1 and data3 both start at Sunday 02:30. If these hosts have 1 Gbit ports, the backup leaves little room for replication traffic and queries. ClickHouseBackupHostLoadHigh watches CPU load, which doesn't capture this. Check the port speed, stagger the two hosts, and alert on replication delay rather than load.

  4. Disk growth during long backups. A running BACKUP keeps the parts it's copying alive, so space freed by merges on obs_web isn't reclaimed on data3 until the backup finishes, more than a day for a full. Watch data3's free disk during the first monthly full.

  5. The upgrade runbook only works if run on both hosts (Runbooks.md:313, :329). run --keep, run --full and release each act only on the host they're run on. If data1 is forgotten, its pre-upgrade restore points are pruned once its new chains complete.

    • Also, release isn't scoped to the job's own tables. Both hosts share prod/ooni/ in ooni-clickhouse-backup, so a release on data3 also removes data1's pins with that label.
  6. A skipped table raises no alert. A table whose name fails SAFE_NAME is logged at ooni_clickhouse_backup.py:466-468, but not counted as failed or given a metric. The cluster check (check_cluster) also treats it as covered. It would never be backed up and nothing would fire. Count it as failed.

Low

  • RocksDB and Join tables keep about two weeks of history, not "a month or two". They take a full every run, so each run starts a new chain (:576), and keep_chains: 2 keeps two weeks.
  • Tables aren't consistent with each other. They're backed up hours to a day or more apart, so a restored materialized view and its source won't match. Worth a line in the restore section.
  • A table can overlap with the next. If polling gives up after 10 minutes (:521-524), the run moves to the next table while the earlier BACKUP is still running in ClickHouse, so two uploads share the link at once.
  • Alert noise:
    • ClickHouseBackupFailed stays true until the next weekly run, so it repeats for a week.
    • ClickHouseBackupCompleted also fires for manual --table runs and for jobs with zero tables.
    • ClickHouseBackupMissing and ClickHouseBackupHostLoadHigh hard-code host names.
  • R2's own limits aren't tested. CI uses MinIO, which accepts unequal part sizes and has no 10,000-part limit. Do one small run against a scratch R2 bucket before the first production full.
  • Nit: ooni-clickhouse-backup.service has WantedBy=multi-user.target. If someone enables the service, a backup starts on every boot. The timer is enough.

…ivate job

None of the tables needs a bucket of its own, so data3's measurements job
now backs up msmt_feedback, faulty_measurements and url_priorities too.
…ait for backups on stop

The credentials file had no handler, and the runbook's systemctl reload
only makes ClickHouse reopen its logs (SIGHUP). ClickHouse rereads config.d
by itself within seconds (checked on 24.8.6.70, for a changed file and a
new one); the handler runs SYSTEM RELOAD CONFIG to apply it at once and to
fail the play on a bad config.

shutdown_wait_backups_and_restores off: a restart during the monthly full,
e.g. for a security update, otherwise hangs for a day or more
(TimeoutStopSec=infinity). ClickHouse reads it at startup only
(system.server_settings: changeable_without_restart = No), so it takes
effect from the next restart.
The script's config held the admin password, which has
access_management. The backup user can take backups and nothing more:
SELECT and BACKUP on ooni.*, S3 and CREATE TEMPORARY TABLE for the
EmbeddedRocksDB/Join export, REMOTE for the cluster check, SELECT on
system.parts and system.backups. It can't restore, insert or drop.
Checked on 24.8.6.70 one grant at a time; with the interserver secret,
the localhost-only user works for clusterAllReplicas too.

On 24.8, S3 lets the user run s3() on any URL: grants can't name one, and
remote_url_allow_hosts limits hosts, not paths, for every user on the
server (and BACKUP ignores it). 25.8 grants a URL regexp and enforces it
(checked on 25.8.33.6), so after the upgrade S3 is to be replaced with
WRITE ON S3('https://<account id>.r2.cloudflarestorage.com/ooni-clickhouse-backup/.*').
The runbook's upgrade section says how; the clickhouse role's grant
template can't render that grant yet.

The tests create the user with the grants read from
group_vars/clickhouse/vars.yml and run the script as it.

Needs /oonidevops/secrets/clickhouse_backup_password in SSM, and the
clickhouse role deployed on data1-3 before the backup role.
…ag and read-only replicas

A running BACKUP keeps the parts it copies, so the space merges would free
stays used until it ends, more than a day for a full:
ClickHouseBackupDiskFilling fires when, during a backup, a disk fills
within a day at the last 6 hours' rate. ClickHouseReplicationLag (over 15
minutes behind for 30) and ClickHouseReplicaReadonly use the cluster's own
metrics (job clickhouse-cluster); a backup on data3 shares its link with
replication fetches.

TextfileJam uses node_exporter's current names (node_textfile_mtime_seconds,
node_time_seconds): the old ones matched nothing on node_exporter 1.8.2.
…els its backup

ClickHouse now cancels running backups when it stops, and BACKUP can't
resume one, so:
- a table whose backup a ClickHouse restart cancelled (it has restarted
  since the table began) is started again once ClickHouse is back, and the
  run goes on. Any other failure isn't retried; the next table waits for
  the failed one's BACKUP if it's still running, rather than share the
  link with it. ClickHouse gone for longer than the script waits for it
  stops the run, rather than fail every table after a 10-minute wait each.
- a table whose name the script can't back up is reported failed
  (ClickHouseBackupFailed) instead of only logged.
- the backup service has no [Install]: enabling it would back up at every
  boot.

A run stopped by a reboot isn't finished automatically: the next run backs
up the tables it hadn't and removes what it left, and the runbook says how
to start one sooner.

Cancelling still waits for the files being uploaded (up to backup_threads,
16) to finish: neither shutdown nor KILL QUERY interrupts one, on 24.8.6.70
or 25.8.33.6. The runbook says how to kill ClickHouse when a reboot can't
wait; nothing does it automatically.

Tests: a restart during a full (obs_web now in 40 parts, more files than
backup_threads, so cancelling has files to skip), ClickHouse killed during
a full, and unit tests for the retry and unsupported names. The runbook also
says to take the upgrade's pinned backups and new fulls on both data3 and
data1, and that release unpins the label for the whole bucket.
…er fails

Fulls and incrementals failing over six months of weekly runs, with two
complete chains checked after every run; a failed incremental removed and
the next one built on the last complete backup; a prune cut short (the
oldest chain's full deleted, an incremental's .backup left) finished by
the next run; and, after ClickHouse is killed during a full, exactly two
complete chains: the new one and the newest from before.

Without the first two, deleting a whole chain when any of its backups is
incomplete went unnoticed.
@aagbsn

aagbsn commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

An Opus 5.5 review as requested by @aagbsn

Review of ooni/devops PR 520 (ClickHouse backups to Cloudflare R2)

The design holds up, but I'd fix two things before the first production run. Any new or unlisted table goes to the bucket meant to be shareable with researchers, so personal data could land there. And one R2 key that can delete every backup sits on the database hosts, where ClickHouse also lets queries use it implicitly. Beyond those, a few operational risks are worth fixing before the first monthly full.

I reviewed all 34 commits (about 2,450 lines across 35 files). I checked table schemas against ooni/backend, but didn't run the container tests.

What's solid: keys never appear in BACKUP queries; R2's equal-part-size rule is handled; delete_objects errors are checked; the metrics file is written atomically; each table has its own backup chain; a backup left running by a killed run is detected before starting a new one. The e2e tests restore every chain and kill ClickHouse mid-backup, which is a strong suite.

High

1. **New tables default to the shareable bucket.** data3's `measurements` job uses `include_tables: ["*"]` (`host_vars/data3…:10`), and only three tables are listed as private. Anything not on that list goes to `ooni-clickhouse-backup`, the bucket the runbook says researchers may get read access to.
   
   * The legacy schema has `accounts` (account ids), `incidents` (`email_address`, `creator_account_id`) and `oonirun` (`author`, an email). All three were in the old `dump-tables-ch.sh` this PR deletes.
   * Check whether any of them, or anything similar, exists in the `ooni` database.
   * Fix: list the measurement tables explicitly. An unclassified table then fires `ClickHouseTableNotBackedUp` and has to be classified, instead of going to the shared bucket.

2. **One credential can wipe both buckets, and ClickHouse hands it out.** The R2 token has Object Read & Write on both buckets and lives on data1 and data3, so a bug in pruning, a mistyped prefix or a compromised host can delete every backup. There's no immutable copy.
   
   * Because the keys are in the `<s3>` endpoint config, ClickHouse uses them for any query whose URL falls under that endpoint. Any ClickHouse user allowed to run `s3()` can therefore read the private bucket (`msmt_feedback`'s account ids) or overwrite backups.
   * Fixes:
     
     * add R2 bucket lock or retention rules at least as long as the pruning age;
     * check which ClickHouse users hold the `S3` source grant;
     * consider a dedicated backup user rather than the admin user.

Medium

3. **The credentials file is installed without a reload.** The template comment says ClickHouse "reloads this file without a restart" (`ooni_backup_s3.xml.j2:6`). The last commit's message says `SYSTEM RELOAD CONFIG` didn't work, and the runbook now says to use `systemctl reload clickhouse-server`. The role has no handler for this, so on first deploy or key rotation ClickHouse can keep the old (or no) credentials and the backup fails. Add a handler and fix the template comment.

4. **Restarting ClickHouse during a full hangs for a day or more.** The runbook notes that `shutdown_wait_backups_and_restores` makes ClickHouse wait for running backups when it stops. Any ClickHouse restart on data3 during the monthly full (an Ansible restart handler, an apt upgrade, a reboot) blocks until the backup finishes. Consider setting it to `false`: an interrupted backup is then cleaned up and retried, which the tests already cover. At least add a check to the ClickHouse role.

5. **Network capacity.** 100 MB/s is about 800 Mbit/s, and data1 and data3 both start at Sunday 02:30. If these hosts have 1 Gbit ports, the backup leaves little room for replication traffic and queries. `ClickHouseBackupHostLoadHigh` watches CPU load, which doesn't capture this. Check the port speed, stagger the two hosts, and alert on replication delay rather than load.

6. **Disk growth during long backups.** A running `BACKUP` keeps the parts it's copying alive, so space freed by merges on `obs_web` isn't reclaimed on data3 until the backup finishes, more than a day for a full. Watch data3's free disk during the first monthly full.

7. **The upgrade runbook only works if run on both hosts** (`Runbooks.md:313`, `:329`). `run --keep`, `run --full` and `release` each act only on the host they're run on. If data1 is forgotten, its pre-upgrade restore points are pruned once its new chains complete.
   
   * Also, `release` isn't scoped to the job's own tables. Both hosts share `prod/ooni/` in `ooni-clickhouse-backup`, so a release on data3 also removes data1's pins with that label.

8. **A skipped table raises no alert.** A table whose name fails `SAFE_NAME` is logged at `ooni_clickhouse_backup.py:466-468`, but not counted as failed or given a metric. The cluster check (`check_cluster`) also treats it as covered. It would never be backed up and nothing would fire. Count it as failed.

Low

* **RocksDB and Join tables keep about two weeks of history, not "a month or two".** They take a full every run, so each run starts a new chain (`:576`), and `keep_chains: 2` keeps two weeks.

* **Tables aren't consistent with each other.** They're backed up hours to a day or more apart, so a restored materialized view and its source won't match. Worth a line in the restore section.

* **A table can overlap with the next.** If polling gives up after 10 minutes (`:521-524`), the run moves to the next table while the earlier `BACKUP` is still running in ClickHouse, so two uploads share the link at once.

* **Alert noise:**
  
  * `ClickHouseBackupFailed` stays true until the next weekly run, so it repeats for a week.
  * `ClickHouseBackupCompleted` also fires for manual `--table` runs and for jobs with zero tables.
  * `ClickHouseBackupMissing` and `ClickHouseBackupHostLoadHigh` hard-code host names.

* **R2's own limits aren't tested.** CI uses MinIO, which accepts unequal part sizes and has no 10,000-part limit. Do one small run against a scratch R2 bucket before the first production full.

* **Nit:** `ooni-clickhouse-backup.service` has `WantedBy=multi-user.target`. If someone enables the service, a backup starts on every boot. The timer is enough.

Thanks for the feedback; I've applied some changes. Note that the disk fill issue wasn't observed on data3 in production, but the alerting is added anyway. Will need to consider whether materialized views are always rebuilt; changing the main one counters_asn_test_lists to PARTITION by week and drop the old data would help.

@aagbsn

aagbsn commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Cloudflare R2 does support Locked Buckets with a time window on them, this is very useful, here's an example snippet:

curl -X PUT "https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/r2/buckets/<BUCKET_NAME>/lock" \
    -H "Authorization: Bearer <API_TOKEN>" \
    -H "Content-Type: application/json" \
    -d '{
        "rules": [
            {
                "id": "retain-30d",
                "enabled": true,
                "prefix": "",
                "condition": {
                    "type": "Age",
                    "maxAgeSeconds": 2592000
                }
            }
        ]
    }'

Clickhouse needs to create and delete a lockfile during the backup.
The solution is to create the backup first to a temporary path, let it complete, the use CopyObject into the time locked path and delete the temporary path. That should work, and although it adds more class A operations, we are well under the limit.

@aagbsn

aagbsn commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Cloudflare R2 does support Locked Buckets with a time window on them, this is very useful, here's an example snippet:

curl -X PUT "https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/r2/buckets/<BUCKET_NAME>/lock" \
    -H "Authorization: Bearer <API_TOKEN>" \
    -H "Content-Type: application/json" \
    -d '{
        "rules": [
            {
                "id": "retain-30d",
                "enabled": true,
                "prefix": "",
                "condition": {
                    "type": "Age",
                    "maxAgeSeconds": 2592000
                }
            }
        ]
    }'

Clickhouse needs to create and delete a lockfile during the backup. The solution is to create the backup first to a temporary path, let it complete, the use CopyObject into the time locked path and delete the temporary path. That should work, and although it adds more class A operations, we are well under the limit.

#536 adds this strategy, but it's a fairly large change.

@aagbsn

aagbsn commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

High

1. **New tables default to the shareable bucket.** data3's `measurements` job uses `include_tables: ["*"]` (`host_vars/data3…:10`), and only three tables are listed as private. Anything not on that list goes to `ooni-clickhouse-backup`, the bucket the runbook says researchers may get read access to.

Known issue. There are no such tables; and no one else holds a read key for these backups.

   * The legacy schema has `accounts` (account ids), `incidents` (`email_address`, `creator_account_id`) and `oonirun` (`author`, an email). All three were in the old `dump-tables-ch.sh` this PR deletes.
   * Check whether any of them, or anything similar, exists in the `ooni` database.

These tables no longer exist

   * Fix: list the measurement tables explicitly. An unclassified table then fires `ClickHouseTableNotBackedUp` and has to be classified, instead of going to the shared bucket.

Not done. May be a good idea, but requires human observation to notice

2. **One credential can wipe both buckets, and ClickHouse hands it out.** The R2 token has Object Read & Write on both buckets and lives on data1 and data3, so a bug in pruning, a mistyped prefix or a compromised host can delete every backup. There's no immutable copy.
   
   * Because the keys are in the `<s3>` endpoint config, ClickHouse uses them for any query whose URL falls under that endpoint. Any ClickHouse user allowed to run `s3()` can therefore read the private bucket (`msmt_feedback`'s account ids) or overwrite backups.
   * Fixes:
     
     * add R2 bucket lock or retention rules at least as long as the pruning age;
     * check which ClickHouse users hold the `S3` source grant;
     * consider a dedicated backup user rather than the admin user.

Dedicated user: 043f63c
Bucket lock is implemented in #536 but this is a big changeset. Needs more review.

Medium

3. **The credentials file is installed without a reload.** The template comment says ClickHouse "reloads this file without a restart" (`ooni_backup_s3.xml.j2:6`). The last commit's message says `SYSTEM RELOAD CONFIG` didn't work, and the runbook now says to use `systemctl reload clickhouse-server`. The role has no handler for this, so on first deploy or key rotation ClickHouse can keep the old (or no) credentials and the backup fails. Add a handler and fix the template comment.

Clickhouse should reload this file automatically on change. 6245443 issues the SYSTEM RELOAD CONFIG.

4. **Restarting ClickHouse during a full hangs for a day or more.** The runbook notes that `shutdown_wait_backups_and_restores` makes ClickHouse wait for running backups when it stops. Any ClickHouse restart on data3 during the monthly full (an Ansible restart handler, an apt upgrade, a reboot) blocks until the backup finishes. Consider setting it to `false`: an interrupted backup is then cleaned up and retried, which the tests already cover. At least add a check to the ClickHouse role.

5. **Network capacity.** 100 MB/s is about 800 Mbit/s, and data1 and data3 both start at Sunday 02:30. If these hosts have 1 Gbit ports, the backup leaves little room for replication traffic and queries. `ClickHouseBackupHostLoadHigh` watches CPU load, which doesn't capture this. Check the port speed, stagger the two hosts, and alert on replication delay rather than load.

Clickhouse doesn't actually manage to use this much capacity on data3 and the constraint is disk I/O. Worth testing again on a faster node, but no significant replication lag was observed with these parameters even with the disk load.

6. **Disk growth during long backups.** A running `BACKUP` keeps the parts it's copying alive, so space freed by merges on `obs_web` isn't reclaimed on data3 until the backup finishes, more than a day for a full. Watch data3's free disk during the first monthly full.

Disk growth wasn't observed when data3 ran backup. Not an issue.

7. **The upgrade runbook only works if run on both hosts** (`Runbooks.md:313`, `:329`). `run --keep`, `run --full` and `release` each act only on the host they're run on. If data1 is forgotten, its pre-upgrade restore points are pruned once its new chains complete.
   
   * Also, `release` isn't scoped to the job's own tables. Both hosts share `prod/ooni/` in `ooni-clickhouse-backup`, so a release on data3 also removes data1's pins with that label.

Important tables should be replicated or converted to replicated types and replicated.

8. **A skipped table raises no alert.** A table whose name fails `SAFE_NAME` is logged at `ooni_clickhouse_backup.py:466-468`, but not counted as failed or given a metric. The cluster check (`check_cluster`) also treats it as covered. It would never be backed up and nothing would fire. Count it as failed.

I think this avoids counting .inner tables created as part of materialized views. We want to use named target tables so these do get backed up and adjust some of these views so they use PARTITION BY as well.

Low

* **RocksDB and Join tables keep about two weeks of history, not "a month or two".** They take a full every run, so each run starts a new chain (`:576`), and `keep_chains: 2` keeps two weeks.

* **Tables aren't consistent with each other.** They're backed up hours to a day or more apart, so a restored materialized view and its source won't match. Worth a line in the restore section.

These probably need to be rebuilt on a restore. Needs investigation

* **A table can overlap with the next.** If polling gives up after 10 minutes (`:521-524`), the run moves to the next table while the earlier `BACKUP` is still running in ClickHouse, so two uploads share the link at once.

* **Alert noise:**
  
  * `ClickHouseBackupFailed` stays true until the next weekly run, so it repeats for a week.
  * `ClickHouseBackupCompleted` also fires for manual `--table` runs and for jobs with zero tables.
  * `ClickHouseBackupMissing` and `ClickHouseBackupHostLoadHigh` hard-code host names.

* **R2's own limits aren't tested.** CI uses MinIO, which accepts unequal part sizes and has no 10,000-part limit. Do one small run against a scratch R2 bucket before the first production full.

Full production backup ran. To

* **Nit:** `ooni-clickhouse-backup.service` has `WantedBy=multi-user.target`. If someone enables the service, a backup starts on every boot. The timer is enough.

Doesn't look like this was resolved yet.

A BACKUP's memory tracker counts memory that isn't there, growing with
what it uploads (ClickHouse issue #66798). On 25.3.14.14 the full
backups of obs_web_ctrl and obs_web failed with MEMORY_LIMIT_EXCEEDED,
"would use 74.27 GiB" for obs_web, more than data3's RAM, against the
9.32 GiB the admin user gets from the default profile. Send
max_memory_usage = 0 with the tool's queries; the server's own limit,
which follows its RSS, still bounds them.
From 25.8, clusterAllReplicas(..., system.tables) also needs SHOW COLUMNS
(ClickHouse issue #116340). Without it the backup script's cluster check
fails with ACCESS_DENIED, seen on 25.8.33.6, and ClickHouseTableNotBackedUp
stops reporting new tables. 25.3 accepts the grant and doesn't need it.
When the query listing the cluster's tables failed, the script only logged
it and kept the last results, so ClickHouseTableNotBackedUp went quiet. It
now writes ooni_clickhouse_backup_cluster_check_failed, and
ClickHouseBackupClusterCheckFailed fires on it.
clickhouse_backup: no per-query memory limit, add grant SHOW COLUMN to backup user
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.

2 participants