jose-lehmkuhl commented on code in PR #51056:
URL: https://github.com/apache/airflow/pull/51056#discussion_r2108009802


##########
providers/postgres/src/airflow/providers/postgres/triggers/postgres_cdc.py:
##########
@@ -0,0 +1,125 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+import asyncio
+import datetime
+from collections.abc import AsyncGenerator
+from datetime import timezone
+
+import psycopg2
+
+from airflow.hooks.base import BaseHook
+from airflow.models import Variable
+from airflow.triggers.base import BaseEventTrigger, TriggerEvent
+
+
+class PostgresCDCEventTrigger(BaseEventTrigger):
+    """
+    A trigger that waits for changes in a PostgreSQL table using polling over 
a timestamp/version column.
+
+    The behavior of this trigger is as follows:
+    - Poll the target table using `SELECT MAX(cdc_column)`.
+    - Compare the result with the stored "last read" value (persisted as an 
Airflow Variable).
+    - If a new value is found (greater than last read), emit a TriggerEvent 
containing metadata.
+    - If no new value is found, sleep for `polling_interval` seconds and 
continue polling.
+
+    :param conn_id: Airflow connection ID for PostgreSQL.
+    :param table: Name of the table to monitor.
+    :param cdc_column: Column representing the change timestamp or version.
+    :param polling_interval: Time (seconds) between polling attempts (default: 
10.0).
+    :param state_key: Key used for persisting CDC state. If None, defaults to 
`{table}_cdc_last_value`.
+    """
+
+    def __init__(
+        self,
+        conn_id: str,
+        table: str,
+        cdc_column: str,
+        polling_interval: float = 10.0,
+        state_key: str | None = None,
+    ):
+        super().__init__()
+        self.conn_id = conn_id
+        self.table = table
+        self.cdc_column = cdc_column
+        self.polling_interval = polling_interval
+        self.state_key = state_key or f"{self.table}_cdc_last_value"
+
+    def serialize(self) -> tuple[str, dict]:
+        """Serialize the trigger's configuration for persistence and 
reconstruction."""
+        return (
+            
"airflow.providers.postgres.triggers.postgres_cdc.PostgresCDCEventTrigger",
+            {
+                "conn_id": self.conn_id,
+                "table": self.table,
+                "cdc_column": self.cdc_column,
+                "polling_interval": self.polling_interval,
+                "state_key": self.state_key,
+            },
+        )
+
+    async def run(self) -> AsyncGenerator[TriggerEvent, None]:
+        """Run the asynchronous polling loop to detect new changes in the 
monitored table."""
+        conn = BaseHook.get_connection(self.conn_id)
+
+        while True:
+            try:
+                with psycopg2.connect(
+                    host=conn.host,
+                    port=conn.port,
+                    dbname=conn.schema,
+                    user=conn.login,
+                    password=conn.password,
+                ) as pg_conn:
+                    with pg_conn.cursor() as cursor:
+                        cursor.execute(f"SELECT MAX({self.cdc_column}) FROM 
{self.table}")
+                        result = cursor.fetchone()
+                        max_value: datetime.datetime | None = result[0]
+
+                        if max_value is not None:
+                            if max_value.tzinfo is None:
+                                max_value = 
max_value.replace(tzinfo=timezone.utc)
+
+                            max_iso = max_value.isoformat()
+
+                            last_value = Variable.get(self.state_key, 
default_var=None)
+                            if last_value:
+                                last_dt = 
datetime.datetime.fromisoformat(last_value)
+                                if last_dt.tzinfo is None:
+                                    last_dt = 
last_dt.replace(tzinfo=timezone.utc)
+                            else:
+                                last_dt = datetime.datetime(1970, 1, 1, 
tzinfo=max_value.tzinfo)
+
+                            if max_value > last_dt:
+                                self.log.info("New change detected: %s (iso: 
%s)", max_value, max_iso)
+                                yield TriggerEvent(

Review Comment:
   Thanks for raising these important points!
   
   I completely agree that relying on the DAG author to manage state 
persistence introduces risks of inconsistency, especially in scenarios with 
multiple AssetWatchers or when variables are deleted or forgotten.
   
   In the current implementation, the state_key is explicitly configurable when 
initializing PostgresCDCEventTrigger. If multiple AssetWatchers are configured 
for the same table but with different state_key values, they will maintain 
independent state, avoiding direct conflicts. Of course, if users accidentally 
reuse the same state_key for multiple watchers, it could lead to unexpected 
behaviors.
   
   Given the current design and behavior of triggers regarding state 
persistence, this approach seemed like a simple and native way to address the 
problem without adding complexity or requiring external solutions.
   
   Perhaps there's room for a more integrated or standardized mechanism within 
Airflow's Asset/Trigger ecosystem to manage this kind of ephemeral or durable 
state safely. I'm happy to collaborate further on possible improvements in this 
area!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to