id: world-bank-indicator-revision-aware-loader
namespace: company.team
description: |
Load a World Bank development indicator (GDP, inflation, population, ...) for every
country and detect what changed since the last run: new periods published, historical
values silently revised, and values withdrawn. Statistical offices restate past years
with every release; a loader that only appends new rows keeps stale history and gets
year-over-year figures wrong. This flow keeps the latest values and a revision log as
Parquet files in Kestra's internal storage, diffs each release against them in DuckDB,
and alerts when a revision is larger than the tolerance.
inputs:
- id: indicator
type: STRING
defaults: NY.GDP.MKTP.CD
description: World Bank indicator code (GDP current US$ by default). Browse
codes at https://data.worldbank.org/indicator.
- id: countries
type: STRING
defaults: all
description: "`all`, or ISO3 codes separated by semicolons (for example
`IND;USA;BRA`). `all` includes the regional and income-group aggregates
the API returns."
- id: date_range
type: STRING
defaults: "2015:2026"
description: Year range as start:end. Keep it wide enough to catch revisions of
past years, not only the newest release.
- id: revision_tolerance
type: FLOAT
defaults: 0.01
description: Relative change of an already published value that counts as a
material revision (0.01 = 1 percent). Smaller changes are logged but do
not alert.
triggers:
- id: weekly_refresh
type: io.kestra.plugin.core.trigger.Schedule
cron: "0 7 * * 1"
description: The World Bank refreshes most indicators a few times a year; a
weekly check costs one request and catches the release within a week.
tasks:
- id: fetch_indicator
type: io.kestra.plugin.core.http.Download
description: One request returns every country and year as JSON (the response is
`[metadata, rows]`); the file lands in internal storage so DuckDB can read
it directly.
uri: "https://api.worldbank.org/v2/country/{{ inputs.countries | urlencode
}}/indicator/{{ inputs.indicator | urlencode
}}?format=json&per_page=20000&date={{ inputs.date_range }}"
headers:
Accept: application/json
- id: previous_values
type: io.kestra.plugin.core.kv.Get
key: "wb_values_{{ inputs.indicator | lower | replace({'.': '_'}) }}"
errorOnMissing: false
description: Internal-storage URI of the Parquet file with the values accepted
by the previous run. Missing on the first run.
- id: previous_log
type: io.kestra.plugin.core.kv.Get
key: "wb_revisions_{{ inputs.indicator | lower | replace({'.': '_'}) }}"
errorOnMissing: false
description: Internal-storage URI of the Parquet revision log built up by previous runs.
- id: bootstrap
type: io.kestra.plugin.core.flow.If
description: First run only. Writes empty Parquet files with the right schema so
the diff task below has one code path, whether or not history exists.
condition: "{{ outputs.previous_values.value is not defined or
outputs.previous_values.value is empty }}"
then:
- id: empty_history
type: io.kestra.plugin.jdbc.duckdb.Queries
url: "jdbc:duckdb:"
outputFiles:
- values
- revisions
sql: |
COPY (SELECT ''::VARCHAR AS indicator, ''::VARCHAR AS country_code, ''::VARCHAR AS iso3, ''::VARCHAR AS country_name, 0::INTEGER AS year, 0::DOUBLE AS value WHERE false) TO '{{ outputFiles.values }}' (FORMAT PARQUET);
COPY (SELECT ''::VARCHAR AS execution_id, now() AS detected_at, ''::VARCHAR AS indicator, ''::VARCHAR AS country_code, ''::VARCHAR AS iso3, ''::VARCHAR AS country_name, 0::INTEGER AS year, 0::DOUBLE AS previous_value, 0::DOUBLE AS current_value, ''::VARCHAR AS change_type, 0::DOUBLE AS relative_change, ''::VARCHAR AS source_last_updated WHERE false) TO '{{ outputFiles.revisions }}' (FORMAT PARQUET);
- id: diff_and_load
type: io.kestra.plugin.jdbc.duckdb.Queries
description: |
DuckDB parses the API response, joins it to the previous values on (country, year) with a
FULL OUTER JOIN and classifies every difference: NEW (a period published for the first
time), REVISED (a published value changed) or WITHDRAWN (a value that disappeared or
became null). The accepted values and the appended revision log are written back as
Parquet; the single result row is the run summary.
url: "jdbc:duckdb:"
fetchType: FETCH_ONE
inputFiles:
indicator.json: "{{ outputs.fetch_indicator.uri }}"
previous_values.parquet: "{{ outputs.previous_values.value ??
outputs.empty_history.outputFiles.values }}"
previous_revisions.parquet: "{{ outputs.previous_log.value ??
outputs.empty_history.outputFiles.revisions }}"
outputFiles:
- values
- revisions
- changes_csv
parameters:
execution_id: "{{ execution.id }}"
tolerance: "{{ inputs.revision_tolerance }}"
sql: |
CREATE TABLE source_meta AS
SELECT json_extract_string(content, '$[0].lastupdated') AS last_updated,
CAST(json_extract(content, '$[0].total') AS INTEGER) AS total_rows
FROM read_text('indicator.json');
CREATE TABLE current AS
SELECT
r->>'$.indicator.id' AS indicator,
r->>'$.country.id' AS country_code,
nullif(r->>'countryiso3code', '') AS iso3,
r->>'$.country.value' AS country_name,
CAST(r->>'date' AS INTEGER) AS year,
TRY_CAST(r->>'value' AS DOUBLE) AS value
FROM (SELECT unnest(from_json(json_extract(content, '$[1]'), '["JSON"]')) AS r FROM read_text('indicator.json'));
CREATE TABLE previous AS SELECT * FROM read_parquet('previous_values.parquet');
CREATE TABLE changes AS
SELECT
:execution_id AS execution_id,
now() AS detected_at,
coalesce(c.indicator, p.indicator) AS indicator,
coalesce(c.country_code, p.country_code) AS country_code,
coalesce(c.iso3, p.iso3) AS iso3,
coalesce(c.country_name, p.country_name) AS country_name,
coalesce(c.year, p.year) AS year,
p.value AS previous_value,
c.value AS current_value,
CASE
WHEN p.value IS NULL THEN 'NEW'
WHEN c.value IS NULL THEN 'WITHDRAWN'
ELSE 'REVISED'
END AS change_type,
CASE WHEN p.value IS NOT NULL AND c.value IS NOT NULL AND p.value <> 0
THEN round((c.value - p.value) / abs(p.value), 6) END AS relative_change,
(SELECT last_updated FROM source_meta) AS source_last_updated
FROM current c
FULL OUTER JOIN previous p ON p.country_code = c.country_code AND p.year = c.year
WHERE p.value IS DISTINCT FROM c.value
AND NOT (p.value IS NULL AND c.value IS NULL);
-- Accepted values for the next run: what the source publishes now (withdrawn values are kept as null).
COPY (SELECT indicator, country_code, iso3, country_name, year, value FROM current ORDER BY country_code, year) TO '{{ outputFiles.values }}' (FORMAT PARQUET);
-- Revision log: history plus this run's changes, except first-run NEW rows (the baseline is not a change).
COPY (
SELECT * FROM read_parquet('previous_revisions.parquet')
UNION ALL
SELECT * FROM changes
WHERE NOT ((SELECT count(*) FROM previous) = 0 AND change_type = 'NEW')
) TO '{{ outputFiles.revisions }}' (FORMAT PARQUET);
-- This run's changes as CSV for the alert and for anyone who wants to open them.
COPY (SELECT country_code, iso3, country_name, year, change_type, previous_value, current_value, relative_change FROM changes ORDER BY abs(coalesce(relative_change, 0)) DESC, year) TO '{{ outputFiles.changes_csv }}' (HEADER, DELIMITER ',');
SELECT
(SELECT last_updated FROM source_meta) AS source_last_updated,
(SELECT count(*) FROM current) AS rows_loaded,
(SELECT count(value) FROM current) AS values_loaded,
(SELECT count(*) FROM previous) = 0 AS is_baseline,
count(*) FILTER (WHERE change_type = 'NEW') AS new_values,
count(*) FILTER (WHERE change_type = 'REVISED') AS revised_values,
count(*) FILTER (WHERE change_type = 'REVISED' AND abs(relative_change) > CAST(:tolerance AS DOUBLE)) AS material_revisions,
count(*) FILTER (WHERE change_type = 'WITHDRAWN') AS withdrawn_values,
coalesce(max(abs(relative_change)) FILTER (WHERE change_type = 'REVISED'), 0) AS max_relative_change,
coalesce(string_agg(coalesce(iso3, country_code) || ' ' || year || ': ' || round(relative_change * 100, 2) || '%', ', ' ORDER BY abs(relative_change) DESC)
FILTER (WHERE change_type = 'REVISED' AND abs(relative_change) > CAST(:tolerance AS DOUBLE)), '') AS top_revisions
FROM changes;
- id: save_values
type: io.kestra.plugin.core.kv.Set
key: "wb_values_{{ inputs.indicator | lower | replace({'.': '_'}) }}"
value: "{{ outputs.diff_and_load.outputFiles.values }}"
- id: save_log
type: io.kestra.plugin.core.kv.Set
key: "wb_revisions_{{ inputs.indicator | lower | replace({'.': '_'}) }}"
value: "{{ outputs.diff_and_load.outputFiles.revisions }}"
- id: alert_on_material_revisions
type: io.kestra.plugin.core.flow.If
description: Alerts only when a published value moved more than the tolerance.
New periods and tiny restatements are logged, not paged.
condition: "{{ outputs.diff_and_load.outputs[0].row.material_revisions > 0 }}"
then:
- id: notify
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
allowFailure: true
description: allowFailure keeps the load green when the webhook is not configured.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": ":rotating_light: World Bank revised history for *{{ inputs.indicator }}* (source updated {{ outputs.diff_and_load.outputs[0].row.source_last_updated }})\n{{ outputs.diff_and_load.outputs[0].row.material_revisions }} value(s) moved more than {{ inputs.revision_tolerance }}: {{ outputs.diff_and_load.outputs[0].row.top_revisions }}\nAlso {{ outputs.diff_and_load.outputs[0].row.new_values }} new, {{ outputs.diff_and_load.outputs[0].row.withdrawn_values }} withdrawn. Rebuild downstream year-over-year figures.\nExecution: {{ kestra.url ?? '' }}/ui/executions/{{ flow.namespace }}/{{ flow.id }}/{{ execution.id }}"
}
else:
- id: no_material_revisions
type: io.kestra.plugin.core.log.Log
message: "{{ inputs.indicator }}: {{
outputs.diff_and_load.outputs[0].row.new_values }} new, {{
outputs.diff_and_load.outputs[0].row.revised_values }} revised (none
above {{ inputs.revision_tolerance }}), {{
outputs.diff_and_load.outputs[0].row.withdrawn_values }} withdrawn."
- id: summary
type: io.kestra.plugin.core.log.Log
message: |
{{ inputs.indicator }} ({{ inputs.countries }}, {{ inputs.date_range }}), source last updated {{ outputs.diff_and_load.outputs[0].row.source_last_updated }}{{ outputs.diff_and_load.outputs[0].row.is_baseline ? ', BASELINE run' : '' }}.
Loaded {{ outputs.diff_and_load.outputs[0].row.values_loaded }} values in {{ outputs.diff_and_load.outputs[0].row.rows_loaded }} country-years.
New {{ outputs.diff_and_load.outputs[0].row.new_values }}, revised {{ outputs.diff_and_load.outputs[0].row.revised_values }} (material {{ outputs.diff_and_load.outputs[0].row.material_revisions }}, max {{ outputs.diff_and_load.outputs[0].row.max_relative_change }}), withdrawn {{ outputs.diff_and_load.outputs[0].row.withdrawn_values }}.
Values: {{ outputs.diff_and_load.outputFiles.values }}
Revision log: {{ outputs.diff_and_load.outputFiles.revisions }}
This run's changes (CSV): {{ outputs.diff_and_load.outputFiles.changes_csv }}
outputs:
- id: summary
type: JSON
value: "{{ outputs.diff_and_load.outputs[0].row }}"
- id: values_parquet
type: FILE
value: "{{ outputs.diff_and_load.outputFiles.values }}"
- id: revision_log_parquet
type: FILE
value: "{{ outputs.diff_and_load.outputFiles.revisions }}"
- id: changes_csv
type: FILE
value: "{{ outputs.diff_and_load.outputFiles.changes_csv }}"