Metadata-Version: 2.5
Name: fw-gear-session-validator
Version: 0.2.4
Summary: Validates a session
Project-URL: Repository, https://gitlab.com/flywheel-io/scientific-solutions/gears/session-validator
Author-email: Flywheel <support@flywheel.io>
License-Expression: MIT
License-File: LICENSE
Keywords: Flywheel,Gears
Classifier: Topic :: Scientific/Engineering
Requires-Python: ~=3.13
Requires-Dist: flywheel-sdk>=20
Requires-Dist: fw-gear<0.4,>=0.3.0
Requires-Dist: reportlab>=4.2
Description-Content-Type: text/markdown

# Session Validator (session-validator)

## Overview

The Session Validator gear checks that a Flywheel session container, including its
acquisitions and files, meets the criteria defined in a user-provided 2020-12
JSONSchema. It records a PASS or FAIL QC result on the session, tags the session
accordingly, and can export the full list of validation errors as a JSON file and/or
a human-readable PDF report. Data managers and study coordinators use it to confirm
that each session is complete (for example, that all expected scans are present and
correctly classified) before downstream processing. Part of the Utility suite.

[[_TOC_]]

### Summary

Validates a Flywheel session container, including its acquisitions and files, against
a user-provided 2020-12 JSON Schema, writing a PASS or FAIL QC result to the session's
metadata. Must be launched at the session level. Optionally saves the full error
report as a JSON or PDF file, and can force re-validation of a session that already
passed.

### Cite

N/A

### License

MIT

### Classification

_Category:_ _analysis_

_Gear Level:_

- [ ] Project
- [ ] Subject
- [X] Session
- [ ] Acquisition
- [ ] Analysis

### Inputs

- _validation_schema_
  - __Name__: _validation_schema_
  - __Type__: _file_
  - __Optional__: _False_
  - __Classification__: _JSON_
  - __Description__: _The schema file to validate the session against_
  - __Notes__: _Must be a valid 2020-12 JSONSchema. See
    [File Specifications](#file-specifications)._

### Config

- _save_validation_report_
  - __Name__: _save_validation_report_
  - __Type__: _boolean_
  - __Description__: _Save the validation report_
  - __Default__: _false_

- _save_pdf_report_
  - __Name__: _save_pdf_report_
  - __Type__: _boolean_
  - __Description__: _Export validation errors to a PDF summary report_
  - __Default__: _false_

- _force_rerun_
  - __Name__: _force_rerun_
  - __Type__: _boolean_
  - __Description__: _Force re-validation even if the session has already passed
    validation_
  - __Default__: _false_

- _debug_
  - __Name__: _debug_
  - __Type__: _boolean_
  - __Description__: _Log debug messages_
  - __Default__: _false_

### Outputs

#### Files

All output files are saved to the session-level analysis container created by the
gear run.

- _validation_report.json_
  - __Name__: _validation_report.json_
  - __Type__: _file_
  - __Optional__: _True_
  - __Classification__: _JSON_
  - __Description__: _JSON file including the full error report from validation._
  - __Notes__: _Only created when `save_validation_report` is `true`. Contains an
    empty list (`[]`) if validation passes. See
    [Understanding Error Structure](#understanding-error-structure)._

- _validation_report.pdf_
  - __Name__: _validation_report.pdf_
  - __Type__: _file_
  - __Optional__: _True_
  - __Classification__: _PDF_
  - __Description__: _Human-readable PDF summary of the validation result and errors._
  - __Notes__: _Only created when `save_pdf_report` is `true`. Created for both
    PASS and FAIL results. See [PDF Report](#pdf-report)._

#### Metadata

The gear writes two things back to the session container:

1. __Tag__: the session is tagged `session-qc-PASS` or `session-qc-FAIL`. On a
   re-run, the previous QC tag is removed before the new one is added.
2. __QC result__: a session-level QC metadata object named `session-validator`. It
   holds information on the gear run (`job_info`: configuration, input file, job ID
   and gear version) and the validation result (`jsonschema-validation`). The
   `jsonschema-validation` object holds the overall state of the validation (`PASS`
   or `FAIL`) and a `data` list with one entry per error reported by the JSONSchema
   validator.

The QC metadata object has the below structure:

```yaml
qc:
  session-validator:
    job_info:
      config:
        debug: <boolean>
        force_rerun: <boolean>
        save_pdf_report: <boolean>
        save_validation_report: <boolean>
      inputs:
        validation_schema:
          file_id: <string>
          file_name: <string>
          parent: <string>
          version: <integer>
      job_id: <string>
      version: <string>
    jsonschema-validation:
      state: <PASS|FAIL>
      data: ["<list of error objects>"]
```

Each error object in the `data` list has the same fields as an entry in
`validation_report.json`. See
[Understanding Error Structure](#understanding-error-structure).

### Pre-requisites

The gear technically has no prerequisites, as validation can be performed entirely
on container labels and file names. However, run both `file-metadata-importer` and
`file-classifier` first if the schema validates container metadata (for example, file
classification or DICOM header values).

#### Prerequisite Gear Runs

A list of gears, in the order they need to be run, when the schema validates file
metadata:

1. __File Metadata Importer__
    - Level: File
2. __File Classifier__
    - Level: File

#### Prerequisite Files

This gear has no prerequisite files beyond the user-provided JSONSchema input file.

#### Prerequisite Metadata

This gear has no prerequisite metadata. However, users may wish to include metadata
fields created by the `file-metadata-importer` and `file-classifier` gears in their
JSONSchema.

## Usage

### Description

This gear validates a Flywheel session container against a JSONSchema. The
JSONSchema file is a required input to the gear and can include validation criteria
on session, acquisition and/or file level metadata. Validation criteria can be
general (for example, `age` is populated with a number) or specific (for example,
the session contains files with specific classifications or header values).

Before validating, the gear builds a nested dictionary of the session: the session
fields at the root, an `acquisitions` list holding each acquisition's fields, and a
`files` list inside each acquisition holding each file's fields (including `modality`,
`classification` and `info`). The schema is evaluated against this dictionary.

The gear skips sessions that already passed validation (tagged `session-qc-PASS`)
unless `force_rerun` is enabled. Sessions tagged `session-qc-FAIL` are always
re-validated.

When `save_pdf_report` is enabled, the gear also produces a PDF report that
summarizes the result for reviewers who do not want to read raw JSON. See
[PDF Report](#pdf-report).

__For practical examples, see the [examples documentation](docs/examples/)__, which
includes:

- Sample JSONSchema files for common use cases
- Example validation error outputs

#### File Specifications

##### _validation_schema_

The validation schema must be a 2020-12 compatible JSONSchema. The gear checks the
schema itself at the start of the run and fails if it is invalid. The schema must
assume the Flywheel hierarchy: the root is the session container, the `acquisitions`
array holds the session's acquisitions, and each acquisition's `files` array holds
its files.

Add a `description` to each rule in the schema. The gear attaches the nearest
`description` found along the failing rule's schema path to each error. This makes
the JSON report, the QC metadata and the PDF report much easier to read.

See the [Use Cases](#use-cases) below for example JSONSchemas.

### Workflow

```mermaid
flowchart LR
    A[validation_schema]:::input --> B{Session level?}
    B -->|No| X[Fail: must run at session level]:::container
    B -->|Yes| C{Already tagged PASS?}
    C -->|Yes, no force_rerun| Z[Exit: already validated]:::container
    C -->|No, or force_rerun| D{Schema valid?}
    D -->|No| Y[Fail: invalid schema]:::container
    D -->|Yes| E[Validate session against schema]:::container
    E --> F[Save JSON report]:::output
    E --> G[Save PDF report]:::output
    E --> H[Tag session PASS/FAIL]:::container
    H --> I[Write QC metadata]:::container

    classDef container fill:#57d,color:#fff
    classDef input fill:#7a9,color:#fff
    classDef output fill:#659,color:#fff
```

Description of workflow:

1. Upload the JSONSchema file to the project attachments (assuming the same
   JSONSchema applies to all sessions in the project).
2. Select the file as the `validation_schema` input and launch the gear at the
   session level.
3. The gear checks that it runs at the session level.
4. The gear checks the session's existing QC tags. If the session is tagged
   `session-qc-PASS` and `force_rerun` is disabled (default), the gear exits without
   re-validating. Otherwise, the previous QC tag is removed.
5. The gear checks that the input JSONSchema is valid.
6. The gear validates the session, its acquisitions and their files against the
   schema.
7. If `save_validation_report` is enabled, the gear saves `validation_report.json`.
8. If `save_pdf_report` is enabled, the gear saves `validation_report.pdf`.
9. The gear tags the session `session-qc-PASS` or `session-qc-FAIL` and writes the
   QC metadata object to the session.

### Use Cases

The conditions listed for each use case are not mutually exclusive, as the various
validation criteria shown in the below use case examples can be combined.  Rather, the
conditions listed for each use case indicate what container properties are used in the
example schemas.

While, there are several ways of setting up a valid JSONSchema (2020-12) for validating
the session container, Flywheel recommends the framework shown below separating the rule
definitions for file and acquisition containers from the validation logic block.  This
framework should generally make the JSONSchema file easier to maintain.

#### Use Case 1: Validate against acquisition labels

___Conditions___:

- [ ] Validate using session container properties
- [X] Validate using acquisition container properties
- [ ] Validate using file level properties

For well-behaved studies, it is possible to validate against acquisition container
labels to quickly determine if a session is missing a required acquisition.

In the below, example jsonschema, we are checking that a session has at _minimum_ one
acquisition with label exactly equal to "T1" and one acquisition with label that
contains the string "T2".  To make maintaining the jsonschema a bit easier, the example
adopts the framework of defining rules in the `"$defs"` section and then leverage the
definitions when creating the validation logic in the subsequent block starting with
`"type": "object"`.

In the two definitions, the example uses `"const"` to require that the acquisition label
be exactly "T1" in the first definition, and `"pattern"` to require that the acquisition
label contain the string "T2" somewhere in the second definition.  In the case of
`"pattern"`, regular expressions can also be used.  For example, regular expressions can
be leveraged to require the acquisition label to start with a string (e.g., `"^T2"`) or
end with a string (e.g., `"T2$"`).

The validation block uses `"allOf"` to require that the session container being
validated _must_ meet _all_ of the rules in the list.  This is more rigid than
`"anyOf"`, where the session container would be considered valid if it met _at least
one_ of the rules in the list.  The validation block also leverages `"minContains"` and
`"maxContains"` to require a session only has one acquisition that satisfies each rule.

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "description": "Schema to validate acquisition labels within a session object",

  "$defs": {
    "acquisition_with_label_T1": {
      "description": "An acquisition whose label must be exactly 'T1'",
      "type": "object",
      "properties": {
        "label": { "const": "T1" }
      },
      "required": ["label"]
    },
    "acquisition_with_label_T2": {
      "description": "An acquisition whose label contains 'T2'",
      "type": "object",
      "properties": {
        "label": { "pattern": "T2" }
      },
      "required": ["label"]
    }
  },

  "type": "object",
  "properties": {
    "acquisitions": {
      "description": "List of acquisitions in this session",
      "type": "array",
      "items": { "type": "object" },
      "allOf": [
        {
          "description": "Require exactly one acquisition with label 'T1'",
          "contains": { "$ref": "#/$defs/acquisition_with_label_T1" },
          "minContains": 1,
          "maxContains": 1
        },
        {
          "description": "Require exactly one acquisition with label 'T2'",
          "contains": { "$ref": "#/$defs/acquisition_with_label_T2" },
          "minContains": 1,
          "maxContains": 1
        }
      ]
    }
  },

  "required": ["acquisitions"]
}
```

#### Use Case 2: Validate against file modality and classification

___Conditions___:

- [ ] Validate using session container properties
- [ ] Validate using acquisition container properties
- [X] Validate using file level properties

To validate that a session has files with expected modalities and/or classifications, it
is possible to leverage the output metadata from the `file-metadata-importer` and
`file-classifier` gears.

Using the framework of having rule definitions separate, means that as validation
criteria are added to the rules, the overall validation block stays relatively fixed.

In the below example, now each acquisition is required to have at least one file with
the specified modality and classification.  Using the rules framework means that we can
make one-to-one matches between the file and acquisition rules.

Note that as validation criteria are added to the `"properties"`, the values for the
respective `"required"` keys need to be updated to ensure that the schema first checks
that the properties exist in the data object being validated before assessing the rules.
In this way, the error for a required property not existing will be separate from a
session that is missing a file or acquisition without the properties defined in the
rules.

Also, note that this example removes the `"label"` requirement from the acquisition
rules.  This schema will simply check if there is an acquisition whose file(s) meets the
file rules without imposing the requirement that the acquisition label be something
specific.  It is easy enough to combine the logic from the previous use case to add the
acquisition label requirement back in if desired.

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "description": "Schema to validate acquisition labels and require files with modality and classification",

  "$defs": {
    "T1_file": {
      "description": "A T1 file with required modality and classification",
      "type": "object",
      "properties": {
        "modality": { "const": "MR" },
        "classification": {
          "type": "object",
          "properties": {
            "Measurement": {
              "description": "Measurment array must contain the value 'T1'",
              "type": "array",
              "items": { "const": "T1" },
              "minItems": 1,
              "maxItems": 1
            },
            "Intent": {
              "description": "Intent array must contain the value 'Structural'",
              "type": "array",
              "items": { "const": "Structural" },
              "minItems": 1,
              "maxItems": 1
            },
            "Features": {
              "description": "Features array must contain both 'MPRAGE' and '3D'",
              "type": "array",
              "minItems": 2,
              "items": { "type": "string" },
              "allOf": [
                { "contains": { "const": "MPRAGE" } },
                { "contains": { "const": "3D" } }
              ]
            }
          },
          "required": ["Measurement", "Intent", "Features"]
        }
      },
      "required": ["modality", "classification"]
    },

    "T2_file": {
      "description": "A T2 file with required modality and classification",
      "type": "object",
      "properties": {
        "modality": { "const": "MR" },
        "classification": {
          "type": "object",
          "properties": {
            "Measurement": {
              "description": "Measurment array must contain the value 'T2'",
              "type": "array",
              "items": { "const": "T2" },
              "minItems": 1,
              "maxItems": 1
            },
            "Intent": {
              "description": "Intent array must contain the value 'Structural'",
              "type": "array",
              "items": { "const": "Structural" },
              "minItems": 1,
              "maxItems": 1
            },
            "Features": {
              "description": "Features array must contain 'Spin-Echo'",
              "type": "array",
              "items": { "const": "Spin-Echo" },
              "minItems": 1
            }
          },
          "required": ["Measurement", "Intent", "Features"]
        }
      },
      "required": ["modality", "classification"]
    },

    "acquisition_with_label_T1": {
      "description": "An acquisition that contains at least one T1 file",
      "type": "object",
      "properties": {
        "files": {
          "type": "array",
          "contains": { "$ref": "#/$defs/T1_file" },
          "minContains": 1
        }
      },
      "required": ["files"]
    },

    "acquisition_with_label_T2": {
      "description": "An acquisition that contains at least one T2 file",
      "type": "object",
      "properties": {
        "files": {
          "type": "array",
          "contains": { "$ref": "#/$defs/T2_file" },
          "minContains": 1
        }
      },
      "required": ["files"]
    }
  },

  "type": "object",
  "properties": {
    "acquisitions": {
      "description": "List of acquisitions in this session",
      "type": "array",
      "items": { "type": "object" },
      "allOf": [
        {
          "description": "Require exactly one acquisition with label 'T1' containing at least one MR file",
          "contains": { "$ref": "#/$defs/acquisition_with_label_T1" },
          "minContains": 1,
          "maxContains": 1
        },
        {
          "description": "Require exactly one acquisition with label 'T2' containing at least one MR file",
          "contains": { "$ref": "#/$defs/acquisition_with_label_T2" },
          "minContains": 1,
          "maxContains": 1
        }
      ]
    }
  },

  "required": ["acquisitions"]
}
```

#### Use Case 3: Validate against file metadata

___Conditions___:

- [ ] Validate using session container properties
- [ ] Validate using acquisition container properties
- [X] Validate using file level properties

While the [dicom-qc](https://gitlab.com/flywheel-io/scientific-solutions/gears/dicom-qc)
gear is specifically suited to validate the full header extracted by
`file-metadata-importer`, it is possible to validate a session against file metadata to
determine if it contains files with the desired imaging parameters or header
information.

In the below partial jsonschema example, we show how to specify a file rule to check
that certain properties of the `file.info.header.dicom` metadata object are the
specified types or values.  Again, since the framework used in these examples separates
out the file and acquisition validation criteria into separate, defined rules, no
additional changes would need to be made to the acquisition rule associated with this
file rule or to the overall jsonschema validation block.

For the added criteria of checking against `file.info.header.dicom` key-value pairs, the
below example shows how to check if the "SeriesDescription" is a non-empty string.  The
combination of `"minLength": 1` and `"pattern": "\\S"` tells the jsonschema to make sure
that "SeriesDescription" contains at least one visible character.  For "Columns", the
schema simply checks that the value is an integer.  And, finally, "ImageType" is checked
to make sure that the string "ORIGINAL" is contained somewhere in the array.  As with
the examples in Use Cases 1 and 2, it is also possible to validate against specific
values (`const`) or patterns (`pattern`) in `file.info.header.dicom` key-value pairs.

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$defs": {
    "CT_file": {
      "type": "object",
      "properties": {
        "modality": { "const": "CT" },
        "classification": {
          "type": "object",
          "properties": {
            "Contrast": {
              "type": "array",
              "items": { "const": "No Contrast" },
              "minItems": 1,
              "maxItems": 1
            },
            "Scan Orientation": {
              "type": "array",
              "items": { "const": "Axial" },
              "minItems": 1,
              "maxItems": 1
            }
          },
          "required": ["Contrast", "Scan Orientation"]
        },
        "info": {
          "type": "object",
          "properties": {
            "header": {
              "type": "object",
              "properties": {
                "dicom": {
                  "type": "object",
                  "properties": {
                    "SeriesDescription": {
                      "description": "Must be string and have at least one character",
                      "type": "string",
                      "minLength": 1,
                      "pattern": "\\S"
                    },
                    "Columns": {
                      "description": "Must be an integer",
                      "type": "integer"
                      },
                    "ImageType": {
                      "description": "Must contain 'ORIGINAL'",
                      "type": "array",
                      "contains": { "const": "ORIGINAL" }
                    }
                  },
                  "required": ["SeriesDescription", "Columns", "ImageType"]
                }
              },
              "required": ["dicom"]
            }
          },
          "required": ["header"]
        }
      },
      "required": ["modality", "classification", "info"]
    },
    ...
  }
}
```

#### Use Case 4: Validate different sessions with different criteria

___Conditions___:

- [X] Validate using session container properties
- [ ] Validate using acquisition container properties
- [ ] Validate using file level properties

For projects that include multi-session data, it is possible to create a single
JSONSchema that includes conditional logic to assess different sessions against
different validation criteria.

This example schema shows how to add conditional logic to first check the session label,
and then based on the session label call specific rules.  So, for this artificial
example, we assume that each subject has two sessions, "T1_session" and "T2_session".
Since, we are not updating the file or acquisition rules, all of the changes are in the
schema validation block.  First, we add this: `"label": { "type": "string" }` to the
session properties.  Then, inside of the `"allOf"` block, we first add an `"if"`
statement to check what the session label is; a `"then"` block is then added to specify
which acquisition rule(s) should be used for validating the session.

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "description": "Schema to validate acquisition labels and require files with modality and classification in specific sessions",

  "$defs": {
    ...
  },

  "type": "object",
  "properties": {
    "label": { "type": "string" },
    "acquisitions": {
      "type": "array",
      "items": { "type": "object" }
    }
  },

  "allOf": [
    {
      "if": { "properties": { "label": { "const": "T1_session" } } },
      "then": {
        "properties": {
          "acquisitions": {
            "type": "array",
            "contains": { "$ref": "#/$defs/acquisition_with_T1_file" },
            "minContains": 1,
            "maxContains": 1
          }
        },
        "required": ["acquisitions"]
      }
    },
    {
      "if": { "properties": { "label": { "const": "T2_session" } } },
      "then": {
        "properties": {
          "acquisitions": {
            "type": "array",
            "contains": { "$ref": "#/$defs/acquisition_with_T2_file" },
            "minContains": 1,
            "maxContains": 1
          }
        },
        "required": ["acquisitions"]
      }
    }
  ],

  "required": ["label", "acquisitions"]
}
```

#### Use Case 5: Validate against session metadata

___Conditions___:

- [X] Validate using session container properties
- [ ] Validate using acquisition container properties
- [ ] Validate using file level properties

It is also possible to include more general validation criteria for session-level
metadata to validate whether the value is of the correct type (e.g., string, number,
boolean, etc.).  Unlike the previous use cases, where the schema imposes required values
and/or patterns of values, with session-level metadata like age and weight, it is more
useful to just check that the metadata exists and is of a specific type.

In the below example jsonschema, we extend the first use case to add a requirement in
the validation block that in addition to the session having the required acquisitions,
the age metadata object is also of type number and has a minimum value of 0.  The schema
could have also leveraged `"maximum"` to set a maximum value.

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "description": "Schema to validate acquisition labels and session-level metadata",

  "$defs": {
    ...
  },

  "type": "object",
  "properties": {
    "age": {
      "description": "Age of the subject at time of session in years",
      "type": "number",
      "minimum": 0
    },
    "acquisitions": {
      "description": "List of acquisitions in this session",
      "type": "array",
      "items": { "type": "object" },
      "allOf": [
        {
          "description": "Require exactly one acquisition with label 'T1'",
          "contains": { "$ref": "#/$defs/acquisition_with_label_T1" },
          "minContains": 1,
          "maxContains": 1
        },
        {
          "description": "Require exactly one acquisition with label 'T2'",
          "contains": { "$ref": "#/$defs/acquisition_with_label_T2" },
          "minContains": 1,
          "maxContains": 1
        }
      ]
    }
  },

  "required": ["age", "acquisitions"]
}
```

#### Use Case 6: Share a PDF validation summary with reviewers

___Conditions___:

- [X] Validate using session container properties
- [X] Validate using acquisition container properties
- [X] Validate using file level properties

Study coordinators or site monitors often need to review why a session failed
without reading raw JSON or browsing the session's QC metadata. Run the gear with
any of the schemas above and enable `save_pdf_report`. The gear saves
`validation_report.pdf` to the analysis container. Reviewers can download it, follow
its links to the job, the session and the schema file in Flywheel, and read each
error with the rule `description` taken from the schema. Enable
`save_validation_report` as well to keep a machine-readable copy of the same errors.

### Interpreting Validation Results

#### Where to Find Validation Errors

After running the Session Validator gear, validation errors are available in up to
three places.

##### 1. Session QC Metadata (always)

Errors are always stored in the session's QC metadata at:

```text
session.info.qc.session-validator.jsonschema-validation.data
```

__Structure__:

```yaml
qc:
  session-validator:
    jsonschema-validation:
      state: "FAIL"
      data:
        - error_message: "..."
          instance_path: "..."
          ...
```

##### 2. validation_report.json (optional output file)

If `save_validation_report` is enabled, the full error report is saved as
`validation_report.json` in the analysis container.

__Structure__:

```json
[
  {
    "error_message": "...",
    "instance_path": "...",
    ...
  }
]
```

##### 3. validation_report.pdf (optional output file)

If `save_pdf_report` is enabled, a PDF summary is saved as `validation_report.pdf`
in the analysis container. See [PDF Report](#pdf-report).

#### PDF Report

The PDF report is intended for human review. It contains:

- __Header__: the report title, the creation timestamp (UTC) and the job ID, linked
  to the job page in Flywheel.
- __Summary__ table:
  - __Number of Errors__
  - __Status__: `PASS` (green) or `FAIL` (red)
  - __Session Location__: the `fw://group/project/subject/session` path, linked to
    the session page in Flywheel
  - __Schema Filename__: the name of the `validation_schema` input file, linked to
    the container that holds it
  - __Schema File Version__: the version of the `validation_schema` input file
- __List of Errors__: one card per validation error, with:
  - __Error Number__
  - __Description__: the nearest `description` from the schema, or "No description
    available"
  - __Schema Definition__: the `$defs` rule name, or "N/A"
  - __Schema Path__
  - __Error Message__

If the session passes, the report shows the summary table followed by "No validation
errors found. The session passed all validation checks."

#### Understanding Error Structure

Each validation error has the following fields:

```json
{
  "error_message": "Human-readable description of what failed",
  "instance_path": "Location in your data where the error occurred",
  "label": "Short identifier for the failing item",
  "schema_path": "Location in your schema where the rule is defined",
  "validator_type": {
    "type": "Type of validation that failed",
    "details": {
      "validator-specific": "Additional context"
    }
  },
  "validator_value": "The constraint value from your schema",
  "schema_definition": "Optional: $ref definition name if applicable",
  "description": "Optional: nearest description found in your schema"
}
```

#### Tips for Debugging Validation Errors

##### 1. Start with `instance_path`

This tells you exactly where in your session the problem is:

- `root` → Session level
- `acquisitions.0` → First acquisition of the session
- `acquisitions.0.files.1` → Second file in the first acquisition
- `acquisitions.0.files.1.modality` → The modality property of that file

##### 2. Check `description` and `schema_definition` for complex errors

`description` holds the nearest `description` found along the failing rule's schema
path. `schema_definition`, when present, tells you which rule in your `$defs` section
failed:

```json
{
  "schema_definition": "acquisition_with_label_T1"
}
```

Go to your schema's `$defs` section and find `acquisition_with_label_T1` to see
exactly what it requires.

##### 3. Use the `label` field

The `label` field is a short identifier for the failing item:

- The `$defs` rule name, when the failing rule references one
- Otherwise, the last element of `instance_path` (for example, `modality` or `age`)
- Otherwise, a fallback based on the validator type (for example, `missing_age`)

##### 4. Review `validator_type.details`

This provides validator-specific context that varies by error type:

| Validator Type | Details Fields | What They Mean |
| ---------------- | --------------- | ---------------- |
| `required` | `missing` | Which fields are missing |
| `type` | `expected`, `found` | Expected vs actual data type |
| `pattern` | `pattern`, `preview` | Required regex and actual value |
| `const` | `expected`, `found` | Expected vs actual value |
| `enum` | `allowed_values`, `found` | Allowed values vs actual value |
| `contains` | `found`, `minContains` | Items checked vs required |
| `minimum` / `maximum` | other constraints of the rule | Sibling constraints (for example, `maximum`) |

##### 5. Understand the `schema_path`

This shows where in your JSONSchema the validation rule is defined, as a
dot-separated path:

```text
$defs.T1_file.properties.modality.const
```

This path tells you: "Go to the `$defs` section, find `T1_file`, look in
`properties`, then `modality`, and you will see a `const` constraint."

For concrete examples of validation errors and how to interpret them, see the
[examples documentation](docs/examples/README.md).

### Logging

This gear uses standard Python logging via the `fw-gear` library. It logs at the
info level as it starts and completes each workflow step, including whether the
session was skipped, validated, and which reports were saved. Warnings and errors
are also logged. Set the `debug` config option to `true` for verbose debug output.

## FAQ

__Q: Why did the gear exit without validating my session?__

A: The session is already tagged `session-qc-PASS`. Enable `force_rerun` to
re-validate it, for example after updating the schema.

__Q: Why did the gear fail with "Cannot run at ... level"?__

A: The gear must be launched at the session level. Launch it from the session
container you want to validate.

__Q: Why did the gear fail with "Invalid JSON schema"?__

A: The `validation_schema` input is not a valid 2020-12 JSONSchema. Check the job log
for the exact schema error.

See also [FAQ.md](FAQ.md).

## Contributing

For information on how to contribute to this gear, please see
[CONTRIBUTING.md](CONTRIBUTING.md).
