Skip to content

createCohort crashes when a RandomPermutation variable has an empty values array #1074

@jimbojw

Description

@jimbojw

Description

Creating a cohort fails with a 500 Internal Server Error when the experiment contains a RandomPermutationVariableConfig with an empty values array.

Root Cause

In generateRandomPermutationValue() (utils/src/variables.utils.ts), numToSelect is clamped to the range [1, maxAvailable]:

const maxAvailable = config.values.length;  // 0
const requestedNum = config.numToSelect ?? maxAvailable;  // 0
const numToSelect = Math.max(1, Math.min(requestedNum, maxAvailable));  // Math.max(1, 0) → 1

When values is empty, maxAvailable is 0, so Math.min(requestedNum, 0) yields 0, then Math.max(1, 0) clamps it up to 1. The function then calls choices(config.values, 1, seedValue), which throws:

Error: Cannot choose 1 distinct values from an array of length 0

This unhandled error propagates up through createCohortInternal()runTransaction() and results in a generic 500 response to the client with no useful error message.

Effect

  • The createCohort cloud function returns a 500 Internal Server Error
  • The client receives no indication of what went wrong—the browser console only shows POST …/createCohort 500 (Internal Server Error)
  • The actual error is only visible in Cloud Functions logs (firebase functions:log --only createCohort)

Options

Option A: Handle the empty-values edge case gracefully

If values is empty and numToSelect is 0 (or unset), return an empty array instead of attempting to select:

if (maxAvailable === 0) {
  if (requestedNum === 0 || requestedNum === undefined) {
    return [];
  }
  throw new HttpsError(
    'invalid-argument',
    `Variable "${config.definition.name}": cannot select ${requestedNum} values from an empty array`
  );
}

Option B: Add validation to reject empty values at save time

Add a check in the variable editor or the experiment write endpoint to prevent saving a RandomPermutationVariableConfig with an empty values array. The validation schema in utils/src/variables.validation.ts currently allows it since values has no minItems constraint.

Option C: Both

Handle the edge case at generation time (Option A) for robustness, and also add validation at save time (Option B) so users get early feedback.

Workaround

The user can edit the experiment in the Experiment Builder, find the variable (named "variable") in the Variables section, and either delete it or add at least one value to its values array.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions