firebase / firebase-tools

The Firebase Command Line Tools
MIT License
3.97k stars 915 forks source link

Deploying firestore.indexes.json breaks singleField exemption index #7374

Open skillitzimberg opened 5 days ago

skillitzimberg commented 5 days ago

[REQUIRED] Environment info

firebase-tools: 13.11.2

Platform: masOS

[REQUIRED] Test case

A scheduled function fails with Error: 9 FAILED_PRECONDITION.

Creating a collectionGroup exemption index in the Firebase Hosting console fixes the problem. However subsequent hosting deploys break the exemption and scheduled function.

Deploying firebase.indexes.json (firebase deploy --only firestore) also breaks exemption index created in the Firebase console, even when the firebase.indexes.json is the same as the output of firebase firestore:indexes. The exemption fails with Error: 9 FAILED_PRECONDITION

Deleting the exemption created in the console & deploying the firebase.indexes.json, creates the expected exemption, but it fails with Error: 9 FAILED_PRECONDITION.

[REQUIRED] Steps to reproduce

Create a collection that includes a subcollection called "reports" & a scheduled function to remove documents in any collection called "reports".

exports.scheduledFunction = functions.pubsub
  .schedule("every 30 minutes")
  .onRun(async () => {
    return Promise.all([_clearOldDocuments()]);
  });

async function _clearOldDocuments() {
  const date = Date.now() - 600000; // 10 min
  const reports = await admin
    .firestore()
    .collectionGroup("reports")
    .where("generateDate", "<", date)
    .get();
  const batch = admin.firestore().batch();
  reports.forEach((d) => batch.delete(d.ref));
  await batch.commit();
}

[REQUIRED] Expected behavior

The scheduled function runs and deletes the expected documents.

Deploying firebase.indexes.json with the following form creates the index exemption and the scheduled function succeeds:

{
  "indexes": [],
  "fieldOverrides": [
    {
      "collectionGroup": "reports",
      "fieldPath": "generateDate",
      "ttl": false,
      "indexes": [
        {
          "order": "ASCENDING",
          "queryScope": "COLLECTION"
        },
        {
          "order": "DESCENDING",
          "queryScope": "COLLECTION"
        },
        {
          "arrayConfig": "CONTAINS",
          "queryScope": "COLLECTION"
        },
        {
          "order": "DESCENDING",
          "queryScope": "COLLECTION_GROUP"
        }
      ]
    }
  ]
}

[REQUIRED] Actual behavior

The scheduled function fails with Error: 9 FAILED_PRECONDITION.

Creating an index collectionGroup exemption in the console fixes the scheduled function run. However, subsequent hosting deployments cause the function to break.

The only way to fix the function is to deploy an empty firebase.indexes.json ({}), deleting the index exemption in the console, and recreating the index in the console. Any hosting deployments break the scheduled function.