You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by GitBox <gi...@apache.org> on 2020/03/06 04:15:07 UTC

[GitHub] [airflow] kaxil opened a new pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

kaxil opened a new pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633
 
 
   **Note to Reviewer**: Please only check the last commit as the first commit is separated to https://github.com/apache/airflow/pull/6788
   Continuation of https://issues.apache.org/jira/browse/AIRFLOW-5944 (https://github.com/apache/airflow/pull/6788)
   
   Store unrendered Task Instance Template Fields in the DAG serialization table. 
   
   
   
   ---
   Issue link: WILL BE INSERTED BY [boring-cyborg](https://github.com/kaxil/boring-cyborg)
   
   Make sure to mark the boxes below before creating PR: [x]
   
   - [x] Description above provides context of the change
   - [x] Commit message/PR title starts with `[AIRFLOW-NNNN]`. AIRFLOW-NNNN = JIRA ID<sup>*</sup>
   - [x] Unit tests coverage for changes (not needed for documentation changes)
   - [x] Commits follow "[How to write a good git commit message](http://chris.beams.io/posts/git-commit/)"
   - [x] Relevant documentation is updated including usage instructions.
   - [x] I will engage committers as explained in [Contribution Workflow Example](https://github.com/apache/airflow/blob/master/CONTRIBUTING.rst#contribution-workflow-example).
   
   <sup>*</sup> For document-only changes commit message can start with `[AIRFLOW-XXXX]`.
   
   ---
   In case of fundamental code change, Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvements+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in [UPDATING.md](https://github.com/apache/airflow/blob/master/UPDATING.md).
   Read the [Pull Request Guidelines](https://github.com/apache/airflow/blob/master/CONTRIBUTING.rst#pull-request-guidelines) for more information.
   

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389315940
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def delete_old_records(
+        cls, task_id: str, dag_id: str,
+        num_to_keep=conf.getint("core", "max_num_rendered_ti_fields_per_task", fallback=0),
+        session: Session = None
+    ):
+        """
+        Keep only Last X (num_to_keep) number of records for a task by deleting others
+
+        :param task_id: Task ID
+        :param dag_id: Dag ID
+        :param num_to_keep: Number of Records to keep
+        :param session: SqlAlchemy Session
+        """
+        if num_to_keep > 0:
+            # Fetch Top X records given dag_id & task_id ordered by Execution Date
+            subq1 = (
+                session
+                .query(cls.dag_id, cls.task_id, cls.execution_date)
+                .filter(cls.dag_id == dag_id, cls.task_id == task_id)
+                .order_by(cls.execution_date.desc())
+                .limit(num_to_keep)
+                .subquery('subq1')
+            )
+
+            # Second Subquery
+            # Workaround for MySQL Limitation (https://stackoverflow.com/a/19344141/5691525)
+            # Limitation: This version of MySQL does not yet support
+            # LIMIT & IN/ALL/ANY/SOME subquery
+            subq2 = (
+                session
+                .query(subq1.c.dag_id, subq1.c.task_id, subq1.c.execution_date)
+                .subquery('subq2')
+            )
+
+        session.query(cls) \
+            .filter(and_(
+                cls.dag_id == dag_id,
+                cls.task_id == task_id,
+                tuple_(cls.dag_id, cls.task_id, cls.execution_date).notin_(subq2))) \
 
 Review comment:
   ```
   The composite IN construct is not supported by all backends, and is
               currently known to work on PostgreSQL, MySQL, and SQLite.
               Unsupported backends will raise a subclass of
               :class:`~sqlalchemy.exc.DBAPIError` when such an expression is
               invoked.
   ```
   We do not support other database engines, but in other places we were able to write code that does not use tuple e.g.  TaskInstance.filter_for_tis

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r391561972
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def delete_old_records(
+        cls, task_id: str, dag_id: str,
+        num_to_keep=conf.getint("core", "max_num_rendered_ti_fields_per_task", fallback=0),
+        session: Session = None
+    ):
+        """
+        Keep only Last X (num_to_keep) number of records for a task by deleting others
+
+        :param task_id: Task ID
+        :param dag_id: Dag ID
+        :param num_to_keep: Number of Records to keep
+        :param session: SqlAlchemy Session
+        """
+        if num_to_keep > 0:
+            # Fetch Top X records given dag_id & task_id ordered by Execution Date
+            subq1 = (
+                session
+                .query(cls.dag_id, cls.task_id, cls.execution_date)
+                .filter(cls.dag_id == dag_id, cls.task_id == task_id)
+                .order_by(cls.execution_date.desc())
+                .limit(num_to_keep)
+                .subquery('subq1')
+            )
+
+            # Second Subquery
+            # Workaround for MySQL Limitation (https://stackoverflow.com/a/19344141/5691525)
+            # Limitation: This version of MySQL does not yet support
+            # LIMIT & IN/ALL/ANY/SOME subquery
+            subq2 = (
+                session
+                .query(subq1.c.dag_id, subq1.c.task_id, subq1.c.execution_date)
+                .subquery('subq2')
+            )
+
+        session.query(cls) \
+            .filter(and_(
+                cls.dag_id == dag_id,
+                cls.task_id == task_id,
+                tuple_(cls.dag_id, cls.task_id, cls.execution_date).notin_(subq2))) \
 
 Review comment:
   Created https://issues.apache.org/jira/browse/AIRFLOW-7045 to deal with it

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] ashb commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r391551185
 
 

 ##########
 File path: tests/serialization/test_dag_serialization.py
 ##########
 @@ -538,6 +539,77 @@ def test_extra_serialized_field_and_multiple_operator_links(self):
         google_link_from_plugin = simple_task.get_extra_links(test_date, GoogleLink.name)
         self.assertEqual("https://www.google.com", google_link_from_plugin)
 
+    class ClassWithCustomAttributes:
+        """
+        Class for testing purpose: allows to create objects with custom attributes in one single statement.
+        """
+
+        def __init__(self, **kwargs):
+            for key, value in kwargs.items():
+                setattr(self, key, value)
+
+        def __str__(self):
+            return "{}({})".format(self.__class__.__name__, str(self.__dict__))
+
+        def __repr__(self):
+            return self.__str__()
+
+        def __eq__(self, other):
+            return self.__dict__ == other.__dict__
+
+        def __ne__(self, other):
+            return not self.__eq__(other)
+
+    @parameterized.expand([
+        (None, None),
+        ([], []),
+        ({}, {}),
+        ("{{ task.task_id }}", "{{ task.task_id }}"),
+        (["{{ task.task_id }}", "{{ task.task_id }}"]),
+        ({"foo": "{{ task.task_id }}"}, {"foo": "{{ task.task_id }}"}),
+        ({"foo": {"bar": "{{ task.task_id }}"}}, {"foo": {"bar": "{{ task.task_id }}"}}),
+        (
+            [{"foo1": {"bar": "{{ task.task_id }}"}}, {"foo2": {"bar": "{{ task.task_id }}"}}],
+            [{"foo1": {"bar": "{{ task.task_id }}"}}, {"foo2": {"bar": "{{ task.task_id }}"}}],
+        ),
+        (
+            {"foo": {"bar": {"{{ task.task_id }}": ["sar"]}}},
+            {"foo": {"bar": {"{{ task.task_id }}": ["sar"]}}}),
+        (
+            ClassWithCustomAttributes(
+                att1="{{ task.task_id }}", att2="{{ task.task_id }}", template_fields=["att1"]),
+            "ClassWithCustomAttributes("
+            "{'att1': '{{ task.task_id }}', 'att2': '{{ task.task_id }}', 'template_fields': ['att1']})",
+        ),
+        (
+            ClassWithCustomAttributes(nested1=ClassWithCustomAttributes(att1="{{ task.task_id }}",
+                                                                        att2="{{ task.task_id }}",
+                                                                        template_fields=["att1"]),
+                                      nested2=ClassWithCustomAttributes(att3="{{ task.task_id }}",
+                                                                        att4="{{ task.task_id }}",
+                                                                        template_fields=["att3"]),
+                                      template_fields=["nested1"]),
+            "ClassWithCustomAttributes("
+            "{'nested1': ClassWithCustomAttributes({'att1': '{{ task.task_id }}', "
+            "'att2': '{{ task.task_id }}', 'template_fields': ['att1']}), "
+            "'nested2': ClassWithCustomAttributes({'att3': '{{ task.task_id }}', "
+            "'att4': '{{ task.task_id }}', 'template_fields': ['att3']}), 'template_fields': ['nested1']})",
+        ),
+    ])
+    def test_templated_fields_exist_in_serialized_dag(self, templated_field, expected_field):
+        """
+        Test that templated_fields exists for all Operators in Serialized DAG
 
 Review comment:
   ```suggestion
           Test that templated_fields exists for all Operators in Serialized DAG
           
           Since we don't want to inflate arbitrary python objects (it poses a RCE/security risk etc.) we want check that non-"basic" objects are turned in to strings after deserializing.
   ```

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389959475
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def delete_old_records(
+        cls, task_id: str, dag_id: str,
+        num_to_keep=conf.getint("core", "max_num_rendered_ti_fields_per_task", fallback=0),
+        session: Session = None
+    ):
+        """
+        Keep only Last X (num_to_keep) number of records for a task by deleting others
+
+        :param task_id: Task ID
+        :param dag_id: Dag ID
+        :param num_to_keep: Number of Records to keep
+        :param session: SqlAlchemy Session
+        """
+        if num_to_keep > 0:
+            # Fetch Top X records given dag_id & task_id ordered by Execution Date
+            subq1 = (
+                session
+                .query(cls.dag_id, cls.task_id, cls.execution_date)
+                .filter(cls.dag_id == dag_id, cls.task_id == task_id)
+                .order_by(cls.execution_date.desc())
+                .limit(num_to_keep)
+                .subquery('subq1')
+            )
+
+            # Second Subquery
+            # Workaround for MySQL Limitation (https://stackoverflow.com/a/19344141/5691525)
+            # Limitation: This version of MySQL does not yet support
+            # LIMIT & IN/ALL/ANY/SOME subquery
+            subq2 = (
 
 Review comment:
   Do you think it might be inefficient? We are just fetching all the results (`*`) from the results of subquery1. 
   
   The only reason we use 2 subqueries is because of the limitation with MySQL

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389957387
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
 
 Review comment:
   It is a separate method as in the future we might want to add some validation or might want to modify the parameters. 
   
   Also, we don't "commit" inside this function and let the caller decide when to save this object to Database when re-using the session.

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] codecov-io edited a comment on issue #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on issue #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#issuecomment-596834730
 
 
   # [Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=h1) Report
   > Merging [#7633](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=desc) into [master](https://codecov.io/gh/apache/airflow/commit/e6af02fdf4fa431739f49e444c93c54ca9f5a8e0&el=desc) will **decrease** coverage by `26.82%`.
   > The diff coverage is `95.95%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/airflow/pull/7633/graphs/tree.svg?width=650&height=150&src=pr&token=WdLKlKHOAU)](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=tree)
   
   ```diff
   @@             Coverage Diff             @@
   ##           master    #7633       +/-   ##
   ===========================================
   - Coverage   86.99%   60.17%   -26.83%     
   ===========================================
     Files         904      906        +2     
     Lines       43728    43829      +101     
   ===========================================
   - Hits        38043    26375    -11668     
   - Misses       5685    17454    +11769     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=tree) | Coverage Δ | |
   |---|---|---|
   | [airflow/models/taskinstance.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvdGFza2luc3RhbmNlLnB5) | `94.97% <88.88%> (-0.16%)` | :arrow_down: |
   | [airflow/models/renderedtifields.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvcmVuZGVyZWR0aWZpZWxkcy5weQ==) | `95.83% <95.83%> (ø)` | |
   | [airflow/models/\_\_init\_\_.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvX19pbml0X18ucHk=) | `91.30% <100.00%> (+0.39%)` | :arrow_up: |
   | [airflow/models/dagbag.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvZGFnYmFnLnB5) | `89.74% <100.00%> (ø)` | |
   | [airflow/serialization/helpers.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9zZXJpYWxpemF0aW9uL2hlbHBlcnMucHk=) | `100.00% <100.00%> (ø)` | |
   | [airflow/serialization/serialized\_objects.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9zZXJpYWxpemF0aW9uL3NlcmlhbGl6ZWRfb2JqZWN0cy5weQ==) | `90.55% <100.00%> (+0.35%)` | :arrow_up: |
   | [airflow/www/views.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy93d3cvdmlld3MucHk=) | `76.29% <100.00%> (+0.16%)` | :arrow_up: |
   | [airflow/providers/amazon/aws/hooks/kinesis.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9wcm92aWRlcnMvYW1hem9uL2F3cy9ob29rcy9raW5lc2lzLnB5) | `0.00% <0.00%> (-100.00%)` | :arrow_down: |
   | [airflow/providers/apache/livy/sensors/livy.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9wcm92aWRlcnMvYXBhY2hlL2xpdnkvc2Vuc29ycy9saXZ5LnB5) | `0.00% <0.00%> (-100.00%)` | :arrow_down: |
   | [airflow/providers/google/suite/hooks/sheets.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9wcm92aWRlcnMvZ29vZ2xlL3N1aXRlL2hvb2tzL3NoZWV0cy5weQ==) | `0.00% <0.00%> (-100.00%)` | :arrow_down: |
   | ... and [304 more](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree-more) | |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=continue).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=footer). Last update [e6af02f...11aa864](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
   

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Display Rendered template_fields without accessing Dagfiles

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Display Rendered template_fields without accessing Dagfiles
URL: https://github.com/apache/airflow/pull/7633#discussion_r391614501
 
 

 ##########
 File path: tests/serialization/test_dag_serialization.py
 ##########
 @@ -538,6 +539,77 @@ def test_extra_serialized_field_and_multiple_operator_links(self):
         google_link_from_plugin = simple_task.get_extra_links(test_date, GoogleLink.name)
         self.assertEqual("https://www.google.com", google_link_from_plugin)
 
+    class ClassWithCustomAttributes:
+        """
+        Class for testing purpose: allows to create objects with custom attributes in one single statement.
+        """
+
+        def __init__(self, **kwargs):
+            for key, value in kwargs.items():
+                setattr(self, key, value)
+
+        def __str__(self):
+            return "{}({})".format(self.__class__.__name__, str(self.__dict__))
+
+        def __repr__(self):
+            return self.__str__()
+
+        def __eq__(self, other):
+            return self.__dict__ == other.__dict__
+
+        def __ne__(self, other):
+            return not self.__eq__(other)
+
+    @parameterized.expand([
+        (None, None),
+        ([], []),
+        ({}, {}),
+        ("{{ task.task_id }}", "{{ task.task_id }}"),
+        (["{{ task.task_id }}", "{{ task.task_id }}"]),
+        ({"foo": "{{ task.task_id }}"}, {"foo": "{{ task.task_id }}"}),
+        ({"foo": {"bar": "{{ task.task_id }}"}}, {"foo": {"bar": "{{ task.task_id }}"}}),
+        (
+            [{"foo1": {"bar": "{{ task.task_id }}"}}, {"foo2": {"bar": "{{ task.task_id }}"}}],
+            [{"foo1": {"bar": "{{ task.task_id }}"}}, {"foo2": {"bar": "{{ task.task_id }}"}}],
+        ),
+        (
+            {"foo": {"bar": {"{{ task.task_id }}": ["sar"]}}},
+            {"foo": {"bar": {"{{ task.task_id }}": ["sar"]}}}),
+        (
+            ClassWithCustomAttributes(
+                att1="{{ task.task_id }}", att2="{{ task.task_id }}", template_fields=["att1"]),
+            "ClassWithCustomAttributes("
+            "{'att1': '{{ task.task_id }}', 'att2': '{{ task.task_id }}', 'template_fields': ['att1']})",
+        ),
+        (
+            ClassWithCustomAttributes(nested1=ClassWithCustomAttributes(att1="{{ task.task_id }}",
+                                                                        att2="{{ task.task_id }}",
+                                                                        template_fields=["att1"]),
+                                      nested2=ClassWithCustomAttributes(att3="{{ task.task_id }}",
+                                                                        att4="{{ task.task_id }}",
+                                                                        template_fields=["att3"]),
+                                      template_fields=["nested1"]),
+            "ClassWithCustomAttributes("
+            "{'nested1': ClassWithCustomAttributes({'att1': '{{ task.task_id }}', "
+            "'att2': '{{ task.task_id }}', 'template_fields': ['att1']}), "
+            "'nested2': ClassWithCustomAttributes({'att3': '{{ task.task_id }}', "
+            "'att4': '{{ task.task_id }}', 'template_fields': ['att3']}), 'template_fields': ['nested1']})",
+        ),
+    ])
+    def test_templated_fields_exist_in_serialized_dag(self, templated_field, expected_field):
+        """
+        Test that templated_fields exists for all Operators in Serialized DAG
 
 Review comment:
   Updated

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] ashb commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r391549359
 
 

 ##########
 File path: tests/www/test_views.py
 ##########
 @@ -1922,6 +1922,24 @@ def test_rendered_view(self, get_dag_function):
         resp = self.client.get(url, follow_redirects=True)
         self.check_content_in_response("testdag__testtask__20200301", resp)
 
+    @mock.patch('airflow.www.views.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.models.taskinstance.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.www.views.dagbag.get_dag')
+    def test_rendered_view_for_unexecuted_tis(self, get_dag_function):
+        """
+        Test that the Rendered View is able to show rendered values
+        even for TIs that have not yet executed
+        """
+        get_dag_function.return_value = SerializedDagModel.get(self.dag.dag_id).dag
+
+        self.assertEqual(self.task.bash_command, '{{ task_instance_key_str }}')
+
+        url = ('rendered?task_id=testtask&dag_id=testdag&execution_date={}'
+               .format(self.percent_encode(self.default_date)))
+
+        resp = self.client.get(url, follow_redirects=True)
+        self.check_content_in_response("testdag__testtask__20200301", resp)
 
 Review comment:
   Nice -- lets display the original error too, as it could be a typo for a built-in filter, and that would help debug it.

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389315624
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def delete_old_records(
+        cls, task_id: str, dag_id: str,
+        num_to_keep=conf.getint("core", "max_num_rendered_ti_fields_per_task", fallback=0),
+        session: Session = None
+    ):
+        """
+        Keep only Last X (num_to_keep) number of records for a task by deleting others
+
+        :param task_id: Task ID
+        :param dag_id: Dag ID
+        :param num_to_keep: Number of Records to keep
+        :param session: SqlAlchemy Session
+        """
+        if num_to_keep > 0:
 
 Review comment:
   ```suggestion
           if num_to_keep < 0:
               return
   ```

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] mik-laj commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r391323555
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def delete_old_records(
+        cls, task_id: str, dag_id: str,
+        num_to_keep=conf.getint("core", "max_num_rendered_ti_fields_per_task", fallback=0),
+        session: Session = None
+    ):
+        """
+        Keep only Last X (num_to_keep) number of records for a task by deleting others
+
+        :param task_id: Task ID
+        :param dag_id: Dag ID
+        :param num_to_keep: Number of Records to keep
+        :param session: SqlAlchemy Session
+        """
+        if num_to_keep > 0:
+            # Fetch Top X records given dag_id & task_id ordered by Execution Date
+            subq1 = (
+                session
+                .query(cls.dag_id, cls.task_id, cls.execution_date)
+                .filter(cls.dag_id == dag_id, cls.task_id == task_id)
+                .order_by(cls.execution_date.desc())
+                .limit(num_to_keep)
+                .subquery('subq1')
+            )
+
+            # Second Subquery
+            # Workaround for MySQL Limitation (https://stackoverflow.com/a/19344141/5691525)
+            # Limitation: This version of MySQL does not yet support
+            # LIMIT & IN/ALL/ANY/SOME subquery
+            subq2 = (
 
 Review comment:
   Oh. Now I understand.

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil merged pull request #7633: [AIRFLOW-6989] Display Rendered template_fields without accessing Dagfiles

Posted by GitBox <gi...@apache.org>.
kaxil merged pull request #7633: [AIRFLOW-6989] Display Rendered template_fields without accessing Dagfiles
URL: https://github.com/apache/airflow/pull/7633
 
 
   

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r391549177
 
 

 ##########
 File path: tests/www/test_views.py
 ##########
 @@ -1922,6 +1922,24 @@ def test_rendered_view(self, get_dag_function):
         resp = self.client.get(url, follow_redirects=True)
         self.check_content_in_response("testdag__testtask__20200301", resp)
 
+    @mock.patch('airflow.www.views.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.models.taskinstance.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.www.views.dagbag.get_dag')
+    def test_rendered_view_for_unexecuted_tis(self, get_dag_function):
+        """
+        Test that the Rendered View is able to show rendered values
+        even for TIs that have not yet executed
+        """
+        get_dag_function.return_value = SerializedDagModel.get(self.dag.dag_id).dag
+
+        self.assertEqual(self.task.bash_command, '{{ task_instance_key_str }}')
+
+        url = ('rendered?task_id=testtask&dag_id=testdag&execution_date={}'
+               .format(self.percent_encode(self.default_date)))
+
+        resp = self.client.get(url, follow_redirects=True)
+        self.check_content_in_response("testdag__testtask__20200301", resp)
 
 Review comment:
   Display original message too

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389315639
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def delete_old_records(
+        cls, task_id: str, dag_id: str,
+        num_to_keep=conf.getint("core", "max_num_rendered_ti_fields_per_task", fallback=0),
 
 Review comment:
   ```suggestion
           num_to_keep=conf.getint("core", "max_num_rendered_ti_fields_per_task", fallback=-1),
   ```

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389902050
 
 

 ##########
 File path: tests/www/test_views.py
 ##########
 @@ -1922,6 +1922,24 @@ def test_rendered_view(self, get_dag_function):
         resp = self.client.get(url, follow_redirects=True)
         self.check_content_in_response("testdag__testtask__20200301", resp)
 
+    @mock.patch('airflow.www.views.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.models.taskinstance.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.www.views.dagbag.get_dag')
+    def test_rendered_view_for_unexecuted_tis(self, get_dag_function):
+        """
+        Test that the Rendered View is able to show rendered values
+        even for TIs that have not yet executed
+        """
+        get_dag_function.return_value = SerializedDagModel.get(self.dag.dag_id).dag
+
+        self.assertEqual(self.task.bash_command, '{{ task_instance_key_str }}')
+
+        url = ('rendered?task_id=testtask&dag_id=testdag&execution_date={}'
+               .format(self.percent_encode(self.default_date)))
+
+        resp = self.client.get(url, follow_redirects=True)
+        self.check_content_in_response("testdag__testtask__20200301", resp)
 
 Review comment:
   It will error with the following message:
   
   ![image](https://user-images.githubusercontent.com/8811558/76248463-4811b780-6239-11ea-844f-f03a60d6b250.png)
   

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389955992
 
 

 ##########
 File path: docs/dag-serialization.rst
 ##########
 @@ -21,7 +21,7 @@
 DAG Serialization
 =================
 
-In order to make Airflow Webserver stateless (almost!), Airflow >=1.10.7 supports
+In order to make Airflow Webserver stateless, Airflow >=1.10.7 supports
 
 Review comment:
   Updated

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Display Rendered template_fields without accessing Dagfiles

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Display Rendered template_fields without accessing Dagfiles
URL: https://github.com/apache/airflow/pull/7633#discussion_r391614742
 
 

 ##########
 File path: tests/www/test_views.py
 ##########
 @@ -1922,6 +1922,24 @@ def test_rendered_view(self, get_dag_function):
         resp = self.client.get(url, follow_redirects=True)
         self.check_content_in_response("testdag__testtask__20200301", resp)
 
+    @mock.patch('airflow.www.views.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.models.taskinstance.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.www.views.dagbag.get_dag')
+    def test_rendered_view_for_unexecuted_tis(self, get_dag_function):
+        """
+        Test that the Rendered View is able to show rendered values
+        even for TIs that have not yet executed
+        """
+        get_dag_function.return_value = SerializedDagModel.get(self.dag.dag_id).dag
+
+        self.assertEqual(self.task.bash_command, '{{ task_instance_key_str }}')
+
+        url = ('rendered?task_id=testtask&dag_id=testdag&execution_date={}'
+               .format(self.percent_encode(self.default_date)))
+
+        resp = self.client.get(url, follow_redirects=True)
+        self.check_content_in_response("testdag__testtask__20200301", resp)
 
 Review comment:
   Updated, screenshot:
   
   ![image](https://user-images.githubusercontent.com/8811558/76525702-3d873600-6464-11ea-906d-9cf0d60b106a.png)
   

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] ashb commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389594566
 
 

 ##########
 File path: tests/www/test_views.py
 ##########
 @@ -1922,6 +1922,24 @@ def test_rendered_view(self, get_dag_function):
         resp = self.client.get(url, follow_redirects=True)
         self.check_content_in_response("testdag__testtask__20200301", resp)
 
+    @mock.patch('airflow.www.views.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.models.taskinstance.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.www.views.dagbag.get_dag')
+    def test_rendered_view_for_unexecuted_tis(self, get_dag_function):
+        """
+        Test that the Rendered View is able to show rendered values
+        even for TIs that have not yet executed
+        """
+        get_dag_function.return_value = SerializedDagModel.get(self.dag.dag_id).dag
+
+        self.assertEqual(self.task.bash_command, '{{ task_instance_key_str }}')
+
+        url = ('rendered?task_id=testtask&dag_id=testdag&execution_date={}'
+               .format(self.percent_encode(self.default_date)))
+
+        resp = self.client.get(url, follow_redirects=True)
+        self.check_content_in_response("testdag__testtask__20200301", resp)
 
 Review comment:
   So we attempt to render the fields anyway? Does this mean that using a user-defined filter etc will just display nothing? Error?
   
   This is possibly more confusing than not rendering the result at all.

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] ashb commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
ashb commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389592678
 
 

 ##########
 File path: docs/dag-serialization.rst
 ##########
 @@ -21,7 +21,7 @@
 DAG Serialization
 =================
 
-In order to make Airflow Webserver stateless (almost!), Airflow >=1.10.7 supports
+In order to make Airflow Webserver stateless, Airflow >=1.10.7 supports
 
 Review comment:
   Somewhere we should mention that 1.10.10 is needed for this last bit.

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389315666
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def delete_old_records(
+        cls, task_id: str, dag_id: str,
+        num_to_keep=conf.getint("core", "max_num_rendered_ti_fields_per_task", fallback=0),
+        session: Session = None
+    ):
+        """
+        Keep only Last X (num_to_keep) number of records for a task by deleting others
+
+        :param task_id: Task ID
+        :param dag_id: Dag ID
+        :param num_to_keep: Number of Records to keep
+        :param session: SqlAlchemy Session
+        """
+        if num_to_keep > 0:
 
 Review comment:
   This will reduce the number of indentations in the code.

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389936969
 
 

 ##########
 File path: tests/www/test_views.py
 ##########
 @@ -1922,6 +1922,24 @@ def test_rendered_view(self, get_dag_function):
         resp = self.client.get(url, follow_redirects=True)
         self.check_content_in_response("testdag__testtask__20200301", resp)
 
+    @mock.patch('airflow.www.views.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.models.taskinstance.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.www.views.dagbag.get_dag')
+    def test_rendered_view_for_unexecuted_tis(self, get_dag_function):
+        """
+        Test that the Rendered View is able to show rendered values
+        even for TIs that have not yet executed
+        """
+        get_dag_function.return_value = SerializedDagModel.get(self.dag.dag_id).dag
+
+        self.assertEqual(self.task.bash_command, '{{ task_instance_key_str }}')
+
+        url = ('rendered?task_id=testtask&dag_id=testdag&execution_date={}'
+               .format(self.percent_encode(self.default_date)))
+
+        resp = self.client.get(url, follow_redirects=True)
+        self.check_content_in_response("testdag__testtask__20200301", resp)
 
 Review comment:
   I am updating it and now it would show the following:
   
   ![image](https://user-images.githubusercontent.com/8811558/76253638-f40bd080-6242-11ea-86bb-246b77804ca4.png)
   

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] potiuk commented on issue #7633: [AIRFLOW-6989] Display Rendered template_fields without accessing Dagfiles

Posted by GitBox <gi...@apache.org>.
potiuk commented on issue #7633: [AIRFLOW-6989] Display Rendered template_fields without accessing Dagfiles
URL: https://github.com/apache/airflow/pull/7633#issuecomment-598681772
 
 
   Whoa! :tada: 

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] codecov-io edited a comment on issue #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on issue #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#issuecomment-596834730
 
 
   # [Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=h1) Report
   > Merging [#7633](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=desc) into [master](https://codecov.io/gh/apache/airflow/commit/e6af02fdf4fa431739f49e444c93c54ca9f5a8e0&el=desc) will **decrease** coverage by `26.82%`.
   > The diff coverage is `95.95%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/airflow/pull/7633/graphs/tree.svg?width=650&height=150&src=pr&token=WdLKlKHOAU)](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=tree)
   
   ```diff
   @@             Coverage Diff             @@
   ##           master    #7633       +/-   ##
   ===========================================
   - Coverage   86.99%   60.17%   -26.83%     
   ===========================================
     Files         904      906        +2     
     Lines       43728    43829      +101     
   ===========================================
   - Hits        38043    26375    -11668     
   - Misses       5685    17454    +11769     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=tree) | Coverage Δ | |
   |---|---|---|
   | [airflow/models/taskinstance.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvdGFza2luc3RhbmNlLnB5) | `94.97% <88.88%> (-0.16%)` | :arrow_down: |
   | [airflow/models/renderedtifields.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvcmVuZGVyZWR0aWZpZWxkcy5weQ==) | `95.83% <95.83%> (ø)` | |
   | [airflow/models/\_\_init\_\_.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvX19pbml0X18ucHk=) | `91.30% <100.00%> (+0.39%)` | :arrow_up: |
   | [airflow/models/dagbag.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvZGFnYmFnLnB5) | `89.74% <100.00%> (ø)` | |
   | [airflow/serialization/helpers.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9zZXJpYWxpemF0aW9uL2hlbHBlcnMucHk=) | `100.00% <100.00%> (ø)` | |
   | [airflow/serialization/serialized\_objects.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9zZXJpYWxpemF0aW9uL3NlcmlhbGl6ZWRfb2JqZWN0cy5weQ==) | `90.55% <100.00%> (+0.35%)` | :arrow_up: |
   | [airflow/www/views.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy93d3cvdmlld3MucHk=) | `76.29% <100.00%> (+0.16%)` | :arrow_up: |
   | [airflow/providers/amazon/aws/hooks/kinesis.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9wcm92aWRlcnMvYW1hem9uL2F3cy9ob29rcy9raW5lc2lzLnB5) | `0.00% <0.00%> (-100.00%)` | :arrow_down: |
   | [airflow/providers/apache/livy/sensors/livy.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9wcm92aWRlcnMvYXBhY2hlL2xpdnkvc2Vuc29ycy9saXZ5LnB5) | `0.00% <0.00%> (-100.00%)` | :arrow_down: |
   | [airflow/providers/google/suite/hooks/sheets.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9wcm92aWRlcnMvZ29vZ2xlL3N1aXRlL2hvb2tzL3NoZWV0cy5weQ==) | `0.00% <0.00%> (-100.00%)` | :arrow_down: |
   | ... and [304 more](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree-more) | |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=continue).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=footer). Last update [e6af02f...11aa864](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
   

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389315783
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def delete_old_records(
+        cls, task_id: str, dag_id: str,
+        num_to_keep=conf.getint("core", "max_num_rendered_ti_fields_per_task", fallback=0),
+        session: Session = None
+    ):
+        """
+        Keep only Last X (num_to_keep) number of records for a task by deleting others
+
+        :param task_id: Task ID
+        :param dag_id: Dag ID
+        :param num_to_keep: Number of Records to keep
+        :param session: SqlAlchemy Session
+        """
+        if num_to_keep > 0:
+            # Fetch Top X records given dag_id & task_id ordered by Execution Date
+            subq1 = (
+                session
+                .query(cls.dag_id, cls.task_id, cls.execution_date)
+                .filter(cls.dag_id == dag_id, cls.task_id == task_id)
+                .order_by(cls.execution_date.desc())
+                .limit(num_to_keep)
+                .subquery('subq1')
+            )
+
+            # Second Subquery
+            # Workaround for MySQL Limitation (https://stackoverflow.com/a/19344141/5691525)
+            # Limitation: This version of MySQL does not yet support
+            # LIMIT & IN/ALL/ANY/SOME subquery
+            subq2 = (
 
 Review comment:
   Do we really need two subqueries? This is a very inefficient query.  If the query is based on JOIN it will be much faster. I know that operating on a Cartesian product is difficult, but I think it's worth trying to do it here.

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] codecov-io commented on issue #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
codecov-io commented on issue #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#issuecomment-596834730
 
 
   # [Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=h1) Report
   > Merging [#7633](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=desc) into [master](https://codecov.io/gh/apache/airflow/commit/29e848d846e4fb5006ad3494d8a50d69129f41c6?src=pr&el=desc) will **increase** coverage by `0.02%`.
   > The diff coverage is `96.93%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/airflow/pull/7633/graphs/tree.svg?width=650&token=WdLKlKHOAU&height=150&src=pr)](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=tree)
   
   ```diff
   @@            Coverage Diff             @@
   ##           master    #7633      +/-   ##
   ==========================================
   + Coverage   86.82%   86.85%   +0.02%     
   ==========================================
     Files         897      899       +2     
     Lines       42869    42961      +92     
   ==========================================
   + Hits        37223    37314      +91     
   - Misses       5646     5647       +1
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=tree) | Coverage Δ | |
   |---|---|---|
   | [airflow/serialization/helpers.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9zZXJpYWxpemF0aW9uL2hlbHBlcnMucHk=) | `100% <100%> (ø)` | |
   | [airflow/serialization/serialized\_objects.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9zZXJpYWxpemF0aW9uL3NlcmlhbGl6ZWRfb2JqZWN0cy5weQ==) | `90.55% <100%> (+0.35%)` | :arrow_up: |
   | [airflow/models/dagbag.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvZGFnYmFnLnB5) | `89.74% <100%> (ø)` | :arrow_up: |
   | [airflow/www/views.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy93d3cvdmlld3MucHk=) | `76.29% <100%> (+0.16%)` | :arrow_up: |
   | [airflow/models/\_\_init\_\_.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvX19pbml0X18ucHk=) | `91.3% <100%> (+0.39%)` | :arrow_up: |
   | [airflow/models/taskinstance.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvdGFza2luc3RhbmNlLnB5) | `94.97% <88.88%> (-0.16%)` | :arrow_down: |
   | [airflow/models/renderedtifields.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvcmVuZGVyZWR0aWZpZWxkcy5weQ==) | `97.87% <97.87%> (ø)` | |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=continue).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=footer). Last update [29e848d...d8c3f45](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
   

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] codecov-io edited a comment on issue #7633: [AIRFLOW-6989] Display Rendered template_fields without accessing Dagfiles

Posted by GitBox <gi...@apache.org>.
codecov-io edited a comment on issue #7633: [AIRFLOW-6989] Display Rendered template_fields without accessing Dagfiles
URL: https://github.com/apache/airflow/pull/7633#issuecomment-596834730
 
 
   # [Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=h1) Report
   > Merging [#7633](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=desc) into [master](https://codecov.io/gh/apache/airflow/commit/78e48ba46a7f721384417ebf8a798dd320632fa8?src=pr&el=desc) will **decrease** coverage by `0.5%`.
   > The diff coverage is `100%`.
   
   [![Impacted file tree graph](https://codecov.io/gh/apache/airflow/pull/7633/graphs/tree.svg?width=650&token=WdLKlKHOAU&height=150&src=pr)](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=tree)
   
   ```diff
   @@            Coverage Diff             @@
   ##           master    #7633      +/-   ##
   ==========================================
   - Coverage   86.99%   86.49%   -0.51%     
   ==========================================
     Files         906      906              
     Lines       43806    43821      +15     
   ==========================================
   - Hits        38110    37903     -207     
   - Misses       5696     5918     +222
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=tree) | Coverage Δ | |
   |---|---|---|
   | [airflow/jobs/base\_job.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9qb2JzL2Jhc2Vfam9iLnB5) | `91.54% <ø> (ø)` | :arrow_up: |
   | [airflow/jobs/scheduler\_job.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9qb2JzL3NjaGVkdWxlcl9qb2IucHk=) | `90.68% <ø> (ø)` | :arrow_up: |
   | [airflow/api/common/experimental/trigger\_dag.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9hcGkvY29tbW9uL2V4cGVyaW1lbnRhbC90cmlnZ2VyX2RhZy5weQ==) | `98.07% <100%> (ø)` | :arrow_up: |
   | [airflow/utils/types.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy91dGlscy90eXBlcy5weQ==) | `100% <100%> (ø)` | :arrow_up: |
   | [airflow/serialization/serialized\_objects.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9zZXJpYWxpemF0aW9uL3NlcmlhbGl6ZWRfb2JqZWN0cy5weQ==) | `90.55% <100%> (+0.35%)` | :arrow_up: |
   | [airflow/api/common/experimental/mark\_tasks.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9hcGkvY29tbW9uL2V4cGVyaW1lbnRhbC9tYXJrX3Rhc2tzLnB5) | `95.51% <100%> (+0.02%)` | :arrow_up: |
   | [airflow/ti\_deps/deps/dagrun\_id\_dep.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy90aV9kZXBzL2RlcHMvZGFncnVuX2lkX2RlcC5weQ==) | `100% <100%> (ø)` | :arrow_up: |
   | [airflow/www/views.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy93d3cvdmlld3MucHk=) | `76.25% <100%> (+0.09%)` | :arrow_up: |
   | [airflow/models/taskinstance.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvdGFza2luc3RhbmNlLnB5) | `94.97% <100%> (+0.16%)` | :arrow_up: |
   | [airflow/models/dagrun.py](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree#diff-YWlyZmxvdy9tb2RlbHMvZGFncnVuLnB5) | `95.68% <100%> (-0.1%)` | :arrow_down: |
   | ... and [16 more](https://codecov.io/gh/apache/airflow/pull/7633/diff?src=pr&el=tree-more) | |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=continue).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=footer). Last update [78e48ba...0c77bd7](https://codecov.io/gh/apache/airflow/pull/7633?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
   

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] mik-laj commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r391323795
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def delete_old_records(
+        cls, task_id: str, dag_id: str,
+        num_to_keep=conf.getint("core", "max_num_rendered_ti_fields_per_task", fallback=0),
+        session: Session = None
+    ):
+        """
+        Keep only Last X (num_to_keep) number of records for a task by deleting others
+
+        :param task_id: Task ID
+        :param dag_id: Dag ID
+        :param num_to_keep: Number of Records to keep
+        :param session: SqlAlchemy Session
+        """
+        if num_to_keep > 0:
+            # Fetch Top X records given dag_id & task_id ordered by Execution Date
+            subq1 = (
+                session
+                .query(cls.dag_id, cls.task_id, cls.execution_date)
+                .filter(cls.dag_id == dag_id, cls.task_id == task_id)
+                .order_by(cls.execution_date.desc())
+                .limit(num_to_keep)
+                .subquery('subq1')
+            )
+
+            # Second Subquery
+            # Workaround for MySQL Limitation (https://stackoverflow.com/a/19344141/5691525)
+            # Limitation: This version of MySQL does not yet support
+            # LIMIT & IN/ALL/ANY/SOME subquery
+            subq2 = (
+                session
+                .query(subq1.c.dag_id, subq1.c.task_id, subq1.c.execution_date)
+                .subquery('subq2')
+            )
+
+        session.query(cls) \
+            .filter(and_(
+                cls.dag_id == dag_id,
+                cls.task_id == task_id,
+                tuple_(cls.dag_id, cls.task_id, cls.execution_date).notin_(subq2))) \
 
 Review comment:
   Yes, but we can write this query in a different way so as not to use the tuple.

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389936969
 
 

 ##########
 File path: tests/www/test_views.py
 ##########
 @@ -1922,6 +1922,24 @@ def test_rendered_view(self, get_dag_function):
         resp = self.client.get(url, follow_redirects=True)
         self.check_content_in_response("testdag__testtask__20200301", resp)
 
+    @mock.patch('airflow.www.views.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.models.taskinstance.STORE_SERIALIZED_DAGS', True)
+    @mock.patch('airflow.www.views.dagbag.get_dag')
+    def test_rendered_view_for_unexecuted_tis(self, get_dag_function):
+        """
+        Test that the Rendered View is able to show rendered values
+        even for TIs that have not yet executed
+        """
+        get_dag_function.return_value = SerializedDagModel.get(self.dag.dag_id).dag
+
+        self.assertEqual(self.task.bash_command, '{{ task_instance_key_str }}')
+
+        url = ('rendered?task_id=testtask&dag_id=testdag&execution_date={}'
+               .format(self.percent_encode(self.default_date)))
+
+        resp = self.client.get(url, follow_redirects=True)
+        self.check_content_in_response("testdag__testtask__20200301", resp)
 
 Review comment:
   I am updating it and now it would show the following:
   
   ![image](https://user-images.githubusercontent.com/8811558/76254290-210cb300-6244-11ea-9a75-fb87613e7a1d.png)
   

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
mik-laj commented on a change in pull request #7633: [AIRFLOW-6989] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389315531
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
 
 Review comment:
   Do we need this method? This only makes it difficult to understand the code, because it is necessary to look at the content of the method to see that it invokes a database query.

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [airflow] kaxil commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table

Posted by GitBox <gi...@apache.org>.
kaxil commented on a change in pull request #7633: [AIRFLOW-6989][depends on AIRFLOW-5944] Store UnRenderedTemplateFields in SerializedDag table
URL: https://github.com/apache/airflow/pull/7633#discussion_r389958399
 
 

 ##########
 File path: airflow/models/renderedtifields.py
 ##########
 @@ -0,0 +1,153 @@
+#
+# 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.
+"""Save Rendered Template Fields """
+import json
+from typing import Optional
+
+from sqlalchemy import JSON, Column, String, and_, exists, tuple_
+from sqlalchemy.orm import Session
+
+from airflow.configuration import conf
+from airflow.models.base import ID_LEN, Base
+from airflow.models.taskinstance import TaskInstance
+from airflow.serialization.serialization_helpers import serialize_template_field
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+
+class RenderedTaskInstanceFields(Base):
+    """
+    Save Rendered Template Fields
+    """
+
+    __tablename__ = "rendered_task_instance_fields"
+
+    dag_id = Column(String(ID_LEN), primary_key=True)
+    task_id = Column(String(ID_LEN), primary_key=True)
+    execution_date = Column(UtcDateTime, primary_key=True)
+    rendered_fields = Column(JSON, nullable=False)
+
+    def __init__(self, ti: TaskInstance, render_templates=True):
+        self.dag_id = ti.dag_id
+        self.task_id = ti.task_id
+        self.task = ti.task
+        self.execution_date = ti.execution_date
+        self.ti = ti
+        if render_templates:
+            ti.render_templates()
+        self.rendered_fields = {
+            field: serialize_template_field(
+                getattr(self.task, field)
+            ) for field in self.task.template_fields
+        }
+
+    def __repr__(self):
+        return f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.execution_date}"
+
+    @classmethod
+    @provide_session
+    def get_templated_fields(cls, ti: TaskInstance, session: Session = None) -> Optional[dict]:
+        """
+        Get templated field for a TaskInstance from the RenderedTaskInstanceFields
+        table.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        :return: Rendered Templated TI field
+        """
+        result = session.query(cls.rendered_fields).filter(
+            cls.dag_id == ti.dag_id,
+            cls.task_id == ti.task_id,
+            cls.execution_date == ti.execution_date
+        ).first()
+
+        if result:
+            rendered_fields = result.rendered_fields
+            if isinstance(rendered_fields, str):
+                rendered_fields = json.loads(rendered_fields)
+            return rendered_fields
+        else:
+            return None
+
+    @classmethod
+    @provide_session
+    def has_templated_fields(cls, ti: TaskInstance, session: Session = None) -> bool:
+        """Checks templated field exist for this ti.
+
+        :param ti: Task Instance
+        :param session: SqlAlchemy Session
+        """
+        # We cant use q.exists() because some databases such as SQL Server don’t allow
+        # an EXISTS expression to be present in the columns clause of a SELECT.
+        # Details: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.exists
+        return session.query(exists().where(
+            and_(cls.dag_id == ti.dag_id,
+                 cls.task_id == ti.task_id,
+                 cls.execution_date == ti.execution_date)
+        )).scalar()
+
+    @provide_session
+    def write(self, session: Session = None):
+        """Write instance to database
+
+        :param session: SqlAlchemy Session
+        """
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def delete_old_records(
+        cls, task_id: str, dag_id: str,
+        num_to_keep=conf.getint("core", "max_num_rendered_ti_fields_per_task", fallback=0),
+        session: Session = None
+    ):
+        """
+        Keep only Last X (num_to_keep) number of records for a task by deleting others
+
+        :param task_id: Task ID
+        :param dag_id: Dag ID
+        :param num_to_keep: Number of Records to keep
+        :param session: SqlAlchemy Session
+        """
+        if num_to_keep > 0:
+            # Fetch Top X records given dag_id & task_id ordered by Execution Date
+            subq1 = (
+                session
+                .query(cls.dag_id, cls.task_id, cls.execution_date)
+                .filter(cls.dag_id == dag_id, cls.task_id == task_id)
+                .order_by(cls.execution_date.desc())
+                .limit(num_to_keep)
+                .subquery('subq1')
+            )
+
+            # Second Subquery
+            # Workaround for MySQL Limitation (https://stackoverflow.com/a/19344141/5691525)
+            # Limitation: This version of MySQL does not yet support
+            # LIMIT & IN/ALL/ANY/SOME subquery
+            subq2 = (
+                session
+                .query(subq1.c.dag_id, subq1.c.task_id, subq1.c.execution_date)
+                .subquery('subq2')
+            )
+
+        session.query(cls) \
+            .filter(and_(
+                cls.dag_id == dag_id,
+                cls.task_id == task_id,
+                tuple_(cls.dag_id, cls.task_id, cls.execution_date).notin_(subq2))) \
 
 Review comment:
   For `TaskInstance.filter_for_tis` we already knew the TIs we wanted to delete. 
   
   In this case, we don't fetch the TIs first and then delete them. We do entire operation on the DB.

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services