id: elasticsearch-vs-postgresql-search-index-reconcile-guard
namespace: company.team
description: |
Reconcile an Elasticsearch search index against its PostgreSQL source of truth. PostgreSQL is read
first for the authoritative keyset and a per-row version, then the indexed documents are read from
Elasticsearch. A document whose key is gone from PostgreSQL is ORPHANED and still answers searches.
A document whose version is behind the row it mirrors is STALE. A row that is not indexed yet is
MISSING and cannot be found. When auto_remediate is set the orphans are deleted and the stale and
missing documents reindexed from the database, each only behind an approval gate. Both sides are
then read again and the run fails if any divergence remains. PostgreSQL is never written.
inputs:
- id: pg_host
type: STRING
displayName: PostgreSQL host
defaults: "localhost"
- id: pg_port
type: INT
displayName: PostgreSQL port
defaults: 5432
- id: pg_db
type: STRING
displayName: PostgreSQL database
defaults: "postgres"
- id: pg_user
type: STRING
displayName: PostgreSQL user
defaults: "postgres"
- id: pg_password
type: STRING
displayName: PostgreSQL password
defaults: "{{ secret('POSTGRES_PASSWORD') }}"
- id: pg_table
type: STRING
displayName: Source of truth table
description: Table that holds the authoritative live rows. A deleted row is gone
from it.
defaults: "product"
- id: pg_key_column
type: STRING
displayName: Key column
description: Primary key column whose value is the Elasticsearch document id.
defaults: "product_id"
- id: pg_version_column
type: STRING
displayName: Version column
description: Column that increases on every update, compared against the
document version.
defaults: "version"
- id: pg_payload_column
type: STRING
displayName: Payload column
description: A column reindexed into the document when a stale or missing
document is rebuilt.
defaults: "title"
- id: es_host
type: STRING
displayName: Elasticsearch host
description: Full URL including scheme and port, for example http://localhost:9200.
defaults: "{{ secret('ELASTICSEARCH_HOST') }}"
- id: es_user
type: STRING
displayName: Elasticsearch user
defaults: "{{ secret('ELASTICSEARCH_USERNAME') }}"
- id: es_password
type: STRING
displayName: Elasticsearch password
defaults: "{{ secret('ELASTICSEARCH_PASSWORD') }}"
- id: es_index
type: STRING
displayName: Search index
description: The index that serves queries and is reconciled against the table.
defaults: "products"
- id: doc_version_field
type: STRING
displayName: Document version field
description: Field in the document source that carries the row version.
defaults: "version"
- id: doc_payload_field
type: STRING
displayName: Document payload field
description: Field in the document source rebuilt from pg_payload_column.
defaults: "title"
- id: batch_limit
type: INT
displayName: Rows per run
description: Upper bound on the keyset read from each side in one run, so a huge
table cannot build an unbounded diff.
defaults: 5000
- id: auto_remediate
type: BOOL
displayName: Auto remediate
defaults: false
- id: dry_run
type: BOOL
displayName: Dry run
description: Must be false, together with auto_remediate, for any delete or
reindex to run.
defaults: true
variables:
jdbc_url: "jdbc:postgresql://{{ inputs.pg_host }}:{{ inputs.pg_port }}/{{
inputs.pg_db }}"
diff_prog: >-
.pg as $pg | .es as $esr | .vf as $vf | ($pg | map({ (.k|tostring): {v: .v,
p: .p} }) | add // {}) as $pgm | (($esr.hits.hits // []) | map({ id:
(._id|tostring), v: (._source[$vf]) })) as $esx | ($esx | map(.id)) as
$esids | ([ $esx[]
| if ($pgm[.id] == null) then {code: "ORPHAN", key: .id, pg_version: null, es_version: .v}
elif ((.v // -1) < $pgm[.id].v) then {code: "STALE", key: .id, pg_version: $pgm[.id].v, es_version: .v, new_version: $pgm[.id].v, new_payload: $pgm[.id].p}
else empty end ]) as $esf
| ([ $pg[] | select(([.k|tostring] - $esids) | length > 0)
| {code: "MISSING", key: (.k|tostring), pg_version: .v, es_version: null, new_version: .v, new_payload: .p} ]) as $miss
| {findings: ($esf + $miss)}
orphan_prog: >-
[.findings[] | select(.code == "ORPHAN") | .key]
upsert_prog: >-
.vf as $vf | .pf as $pf | [.findings[] | select(.code == "STALE" or .code ==
"MISSING")
| {key: .key, doc_str: ({($vf): .new_version, ($pf): .new_payload} | tojson)}]
tasks:
- id: pg_read
type: io.kestra.plugin.jdbc.postgresql.Query
description: Read-only. The authoritative keyset, each row version and the
payload column, in key order.
url: "{{ render(vars.jdbc_url) }}"
username: "{{ inputs.pg_user }}"
password: "{{ inputs.pg_password }}"
fetchType: FETCH
sql: >-
SELECT {{ inputs.pg_key_column }} AS k, {{ inputs.pg_version_column }} AS
v, {{ inputs.pg_payload_column }} AS p FROM {{ inputs.pg_table }} ORDER BY
{{ inputs.pg_key_column }} LIMIT {{ inputs.batch_limit }}
- id: es_read
type: io.kestra.plugin.elasticsearch.Request
description: Read-only. Every indexed document id with its version field, up to
batch_limit hits.
connection:
hosts:
- "{{ inputs.es_host }}"
basicAuth:
username: "{{ inputs.es_user }}"
password: "{{ inputs.es_password }}"
method: GET
endpoint: "{{ inputs.es_index }}/_search"
parameters:
size: "{{ inputs.batch_limit }}"
_source: "{{ inputs.doc_version_field }}"
- id: index_check
type: io.kestra.plugin.core.flow.If
description: The Request task succeeds on any HTTP status, so a non-200 read is
caught here before the diff.
condition: "{{ outputs.es_read.status != 200 }}"
then:
- id: index_unreadable
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Elasticsearch returned HTTP {{ outputs.es_read.status }} for
index {{ inputs.es_index }}. The index must exist and be readable
before it can be reconciled."
- id: diff
type: io.kestra.plugin.core.output.OutputValues
description: Diff both sides. Orphan when the document key is gone from
PostgreSQL, stale when the document version is behind, missing when a row
is not indexed.
values:
result: >-
{{ {'pg': outputs.pg_read.rows, 'es': outputs.es_read.response, 'vf':
inputs.doc_version_field} | jq(vars.diff_prog) | first | toJson }}
- id: plan
type: io.kestra.plugin.core.output.OutputValues
description: The orphan ids to delete and the stale plus missing documents to
reindex from the database row.
values:
orphans: >-
{{ fromJson(outputs.diff.values.result) | jq(vars.orphan_prog) | first |
toJson }}
upserts: >-
{{ {'findings': fromJson(outputs.diff.values.result).findings, 'vf':
inputs.doc_version_field, 'pf': inputs.doc_payload_field} |
jq(vars.upsert_prog) | first | toJson }}
- id: summary
type: io.kestra.plugin.core.log.Log
message: >-
Reconcile of index {{ inputs.es_index }} against {{ render(vars.jdbc_url)
}}: {{ fromJson(outputs.diff.values.result).findings | length }}
divergences ({{ fromJson(outputs.diff.values.result).findings | jq('[.[] |
select(.code=="ORPHAN")] | length') | first }} orphan, {{
fromJson(outputs.diff.values.result).findings | jq('[.[] |
select(.code=="STALE")] | length') | first }} stale, {{
fromJson(outputs.diff.values.result).findings | jq('[.[] |
select(.code=="MISSING")] | length') | first }} missing). {{
fromJson(outputs.diff.values.result).findings | jq('map("\(.code) \(.key)
db=\(.pg_version // "gone") idx=\(.es_version // "none")") | join("; ")')
| first }}
- id: route
type: io.kestra.plugin.core.flow.If
condition: "{{ fromJson(outputs.diff.values.result).findings | length > 0 }}"
then:
- id: alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {'text': 'Elasticsearch vs PostgreSQL reconcile on ' ~ inputs.es_index ~ ': ' ~ (fromJson(outputs.diff.values.result).findings | jq('map("\(.code) \(.key)") | join(", ")') | first) ~ '.' ~ (inputs.auto_remediate and not inputs.dry_run ? ' Remediation armed, waiting for approval.' : ' No change applied (auto_remediate=' ~ inputs.auto_remediate ~ ', dry_run=' ~ inputs.dry_run ~ ').')} | toJson }}
- id: remediate_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.auto_remediate and not inputs.dry_run }}"
then:
- id: approval
type: io.kestra.plugin.core.flow.Pause
description: Hold before any write to the index. Resume with approved true to
apply, anything else leaves the index untouched.
onResume:
- id: approved
type: BOOL
required: false
description: Set true to delete the orphans and reindex the stale and missing
documents.
- id: apply_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approval.onResume.approved ?? false }}"
then:
- id: evict_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ fromJson(outputs.plan.values.orphans) | length > 0 }}"
then:
- id: delete_orphans
type: io.kestra.plugin.elasticsearch.Request
description: Delete the orphan documents by id in one request, then refresh so
the re-read sees the deletions.
connection:
hosts:
- "{{ inputs.es_host }}"
basicAuth:
username: "{{ inputs.es_user }}"
password: "{{ inputs.es_password }}"
method: POST
endpoint: "{{ inputs.es_index }}/_delete_by_query"
parameters:
refresh: "true"
body: >-
{{ {'query': {'ids': {'values':
fromJson(outputs.plan.values.orphans)}}} | toJson }}
- id: delete_ok
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.delete_orphans.status != 200 }}"
then:
- id: delete_failed
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Delete by query returned HTTP {{ outputs.delete_orphans.status
}}: {{ outputs.delete_orphans.response | toJson }}"
- id: reindex_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ fromJson(outputs.plan.values.upserts) | length > 0 }}"
then:
- id: reindex
type: io.kestra.plugin.core.flow.Loop
description: Reindex each stale and missing document from the database row
behind the remediation gate. Serial so the writes do not
race.
concurrencyLimit: 1
values: "{{ outputs.plan.values.upserts }}"
tasks:
- id: put_doc
type: io.kestra.plugin.elasticsearch.Put
connection:
hosts:
- "{{ inputs.es_host }}"
basicAuth:
username: "{{ inputs.es_user }}"
password: "{{ inputs.es_password }}"
index: "{{ inputs.es_index }}"
key: "{{ fromJson(item.value).key }}"
value: "{{ fromJson(item.value).doc_str }}"
refreshPolicy: IMMEDIATE
- id: reverify_pg
type: io.kestra.plugin.jdbc.postgresql.Query
description: Read-only. Read the source of truth again after the writes.
url: "{{ render(vars.jdbc_url) }}"
username: "{{ inputs.pg_user }}"
password: "{{ inputs.pg_password }}"
fetchType: FETCH
sql: >-
SELECT {{ inputs.pg_key_column }} AS k, {{
inputs.pg_version_column }} AS v, {{ inputs.pg_payload_column
}} AS p FROM {{ inputs.pg_table }} ORDER BY {{
inputs.pg_key_column }} LIMIT {{ inputs.batch_limit }}
- id: reverify_es
type: io.kestra.plugin.elasticsearch.Request
description: Read the index again, so the proof comes from Elasticsearch itself.
connection:
hosts:
- "{{ inputs.es_host }}"
basicAuth:
username: "{{ inputs.es_user }}"
password: "{{ inputs.es_password }}"
method: GET
endpoint: "{{ inputs.es_index }}/_search"
parameters:
size: "{{ inputs.batch_limit }}"
_source: "{{ inputs.doc_version_field }}"
- id: reverify_diff
type: io.kestra.plugin.core.output.OutputValues
description: Re-run the same diff. An orphan still indexed, a document still
behind or a row still unindexed is unresolved.
values:
remaining: >-
{{ {'pg': outputs.reverify_pg.rows, 'es':
outputs.reverify_es.response, 'vf':
inputs.doc_version_field} | jq(vars.diff_prog) | first |
toJson }}
- id: verify_result
type: io.kestra.plugin.core.flow.If
condition: "{{ fromJson(outputs.reverify_diff.values.remaining).findings |
length > 0 }}"
then:
- id: remediation_failed
type: io.kestra.plugin.core.execution.Fail
errorMessage: >-
Reconcile did not converge: {{
fromJson(outputs.reverify_diff.values.remaining).findings
| jq('map("\(.code) \(.key)") | join(", ")') | first }}
still diverge. A row may have changed during the run or
the connecting Elasticsearch user may not delete or index
these documents.
else:
- id: remediated
type: io.kestra.plugin.core.log.Log
message: >-
Reconciled and verified: deleted the orphan documents,
reindexed the stale and missing documents, 0 divergence
left.
else:
- id: withheld
type: io.kestra.plugin.core.log.Log
message: "Approval was not granted, so no document was deleted or reindexed. The
divergence stands."
else:
- id: clean
type: io.kestra.plugin.core.log.Log
message: "The index matches the source of truth: every document mirrors a live
row at its current version and every live row is indexed."
errors:
- id: alert_flow_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {'text': 'Elasticsearch vs PostgreSQL reconcile guard failed on ' ~ inputs.es_index ~ ' (execution ' ~ execution.id ~ '). Check the logs.'} | toJson }}
triggers:
- id: hourly
type: io.kestra.plugin.core.trigger.Schedule
description: Shipped disabled and always in safe mode.
cron: "35 * * * *"
disabled: true
inputs:
auto_remediate: false
dry_run: true