airflow: API - Improve error response on missing dag in the dagbag.

Body

Improve error handling when accessing dag via the dag bag. The error response should allow user to know if the dag is found in db and failing to deserialize or just missing from the db. Both status code could still be a 404.

In such pattern:

        dag = request.app.state.dag_bag.get_dag(dag_id)
        if not dag:
            raise HTTPException(status.HTTP_404_NOT_FOUND, f"DAG with dag_id: `{dag_id}` was not found")

related https://github.com/apache/airflow/pull/48776

Currently if deserialization fails, it will blow up with a 500 error.

Committer

  • I acknowledge that I am a maintainer/committer of the Apache Airflow project.

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 16 (10 by maintainers)

Commits related to this issue

Most upvoted comments

Thanks for suggestion. It’s possible that there could be other missing values as well, but they should all result in a RuntimeError(Correct me if I am wrong). For now, I’ll try to use the presence of the airflow dags reserialize message as a check and proceed in that direction.

Great to see a test that can reproduce the error.

Is the following exception the only one we are trying to catch ?

RuntimeError(
                "Encoded dag object has no dag_id key.  You may need to run `airflow dags reserialize`."
            )

If so. yes I believe that catching the RuntimeError + maybe a check on the error message to be sure to not catch another unrelated runtime error should do the trick.

@rawwar I’ve tested this scenario by writing a unit test that directly modifies the _data column in the serialized_dag table to remove the dag_id key from the serialized DAG JSON. The test confirms that it returns a 500 error when invoking the endpoint.

    def test_get_dag_missing_dag_id_in_serialized_data(self, test_client):
        test_dag = DAG(dag_id=TEST_DAG_ID, start_date=datetime(2025, 4, 15), schedule="@once")
        EmptyOperator(task_id="test_task", dag=test_dag)
        test_dag.sync_to_db()
        SerializedDagModel.write_dag(test_dag, bundle_name=TEST_DAG_ID)

        with create_session() as session:
            dag_model = session.scalar(
                select(SerializedDagModel).where(SerializedDagModel.dag_id == TEST_DAG_ID)
            )

            data = dag_model.data
            del data["dag"]["dag_id"]
            session.execute(
                update(SerializedDagModel)
                .where(SerializedDagModel.dag_id == TEST_DAG_ID)
                .values(_data=data)
            )
            session.commit()

        response = test_client.get(f"/dags/{TEST_DAG_ID}")
        assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
        assert "An unexpected error occurred" in response.json()["detail"]

Based on this result, I’ll focus on handling this case during the deserialization process to provide a more meaningful error message instead of a generic 500 error.

@pierrejeambrun I’m not sure if using try-except to catch a RuntimeError and return a 400 response is appropriate in this situation. Do you have a better recommendation?

@pierrejeambrun , I was looking at DagBag.get_dag method. I don’t think we actually deserialize data here. Rather, we just do a query to fetch from DB. Correct me if I am wrong.

I think it is actually. (Which is normal because we end up with a DAG, reading from the SerializedDagModel table from the DB). DagBag.get_dag will call _add_dag_from_db if reading from db. It will access SerializedDagModel.dag which will call SerializedDAG.from_dict that will deserialize.

@giannistbs ok, but I think I’m not very familiar with Airflow yet.

@rawwar Thanks for your suggestion. I will try the test.

Hello @giannistbs I already worked on this. I am preparing to raise a PR. Maybe you can find another issue?

We basically need to wrap dag = request.app.state.dag_bag.get_dag(dag_id) into an exception handler to catch deserialization issue / missing from db.