> For the complete documentation index, see [llms.txt](https://docs.durohub.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.durohub.com/library-configuration/change-order-validations.md).

# Change Order Validations

## Overview

Change Order Validations provide a comprehensive system for ensuring data integrity and enforcing business rules throughout your change management process. This powerful feature allows you to run both built-in system validations and custom validation rules that align with your organization's specific requirements.

## Why Validations Matter

In complex engineering environments, a single oversight can lead to costly errors, production delays, or compliance issues. The validation system helps you:

* **Prevent Errors Early**: Catch issues before changes are approved and implemented
* **Enforce Standards**: Ensure all changes meet your organization's requirements
* **Maintain Consistency**: Apply the same rules across all change orders
* **Provide Transparency**: Give reviewers clear visibility into validation results
* **Enable Custom Logic**: Create organization-specific validation rules

## Understanding Validation Types

The Duro platform provides two types of validations:

### System Validations

Built-in validations run on every change order in every library. Each appears in a run's results under the name below, with `validationType: SYSTEM`. `onFailure` is the value each result reports; see [OnFailure Behavior](#onfailure-behavior) for what blocks submission.

| Name                                                                          | What it checks                                                                                                                                        | `onFailure` |
| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| `Change Order Summary`                                                        | Informational summary of the change order's contents; does not fail                                                                                   | `WARNING`   |
| `Items must not exist in other OPEN Change Orders`                            | No item on this change order is also on another open or resolved change order                                                                         | `ERROR`     |
| `Status tier validation`                                                      | Parents and children have compatible status tiers, and documents on the change order are at or above the status of the component they are attached to | `WARNING`   |
| `Obsolete descendant components`                                              | Warns when an item's assembly tree contains obsolete components                                                                                       | `WARNING`   |
| `Zero-quantity BOM items`                                                     | Warns when an item has BOM lines with a quantity of 0                                                                                                 | `WARNING`   |
| `Components cannot be in DESIGN status`                                       | No component on the change order is in, or moving to, `DESIGN` status                                                                                 | `ERROR`     |
| [`DCO items must stay at their last-released baseline`](#dco-baseline-freeze) | Items on a `DCO` have not drifted from their last-released status and revision                                                                        | `ERROR`     |
| `Released-obsolete components cannot be in a change order`                    | No released-obsolete component is on the change order                                                                                                 | `ERROR`     |
| `Revision Change Type must be valid`                                          | Items set to not bump their revision are still at their released values                                                                               | `ERROR`     |
| `Revision bump must still be applied`                                         | An item that proposes a revision bump has not been put back to its released revision and status by another change order                               | `ERROR`     |
| `NRM components should not carry a revision bump`                             | Warns when a component that is not revision-managed still has a bumping revision change type on its item                                              | `WARNING`   |
| [`Components must have a valid primary source`](#primary-source-required)     | Parts and assemblies have a priced primary source, when the library turns this check on                                                               | `WARNING`   |

Two more are added per library:

* **`<attribute> must be unique`** — one for each attribute that requires unique values. Fails when a component's value for that attribute collides with another non-archived component in the library (`onFailure: ERROR`).
* **`Linked documents should be on the change order`** — when the library adds linked documents to change orders automatically. Warns when an item links a document that is not itself on the change order (`onFailure: WARNING`).

#### DCO baseline freeze

Change orders of type [`DCO`](https://docs.durohub.com/core-concepts/change-orders.md#change-order-types) are revision-frozen, so a built-in validation guards their items against drifting from the last-released baseline. For every item on a DCO, it compares the item's **live** `status` and `revision` to its **last-released baseline** and fails the change order when they no longer match. It fails when any of the following holds:

* the live `status` differs from the baseline `status`;
* the live `revision` differs from the baseline `revision`;
* the item has no releasable baseline (it was never released), or its live component can't be found.

It also fails for an item whose recorded release cannot be trusted, because the part's release history predates reliable release records.

This validation runs on every change order and always passes for types other than `DCO`, so it appears as a passed result in every run. A DCO can only be created from a template that lists `DCO` in `co_types`, which requires template schema `version: '1.1'` or later — see [Change Order Workflows → Choosing a Schema Version](https://docs.durohub.com/library-configuration/change-order-workflows.md#choosing-a-schema-version). Change orders from `'1.0'` templates are always `ECO`, so this validation never runs for them. Because it is checked both when the DCO is submitted and again when it closes, a DCO can't slip through if a concurrent change order releases one of its items in the meantime.

* **At validation and submit**, a failure is a `FAIL` result named `DCO items must stay at their last-released baseline`, whose `errorMessage` lists the items that changed, for example `1 item has changed from its last-released baseline: …`. The change order cannot be submitted until a run passes.
* **When the DCO closes**, or when a DCO item's status or revision is edited, the change is refused with [`DCO_STATUS_CHANGE_NOT_ALLOWED` / `DCO_REVISION_CHANGE_NOT_ALLOWED`](https://docs.durohub.com/advanced-topics/error-handling.md#dco_status_change_not_allowed-dco_revision_change_not_allowed).

#### Primary source required

A built-in validation named **`Components must have a valid primary source`** checks that the parts and assemblies being promoted by a change order can actually be bought. For every item the change order promotes out of `DESIGN` status, the item must have an **active primary source** — a designated [primary](https://docs.durohub.com/core-concepts/sourcing.md#ranking-primary-sources) manufacturer part with a distributor quote that carries a price. A quote priced at `$0` counts as priced and is valid; a missing price is not. A rollup primary source never counts as valid.

Only components in a `PART` or `ASSEMBLY` category are checked. Items whose target status is `DESIGN` are not checked, so early design work is never held up by sourcing data.

This validation is configured per library and has three modes:

| Mode      | Result state | Effect                                               |
| --------- | ------------ | ---------------------------------------------------- |
| `off`     | `PASS`       | Always passes. The result still appears in every run |
| `warning` | `WARNING`    | Surfaces on the change order but does not block it   |
| `error`   | `FAIL`       | Blocks the change order from being submitted         |

`onFailure` is `WARNING` in every mode. In `error` mode the block comes from the `FAIL` state, not from `onFailure`: any `FAIL` result fails the run. Read `state` and `errorMessage` from the run to see which items are missing a priced primary source:

```json
{
  "node": {
    "name": "Components must have a valid primary source",
    "validationType": "SYSTEM",
    "state": "WARNING",
    "onFailure": "WARNING",
    "errorMessage": "2 component(s) missing a valid primary source: …"
  }
}
```

{% hint style="warning" %}
**Fails closed.** Duro resolves sourcing through an internal service. If that service can't be reached, the validation does not silently pass — it reports:

`Could not verify sourcing — vendor-sourcing is temporarily unavailable. Please try validating again.`

Treat this as a transient condition and re-run `changeOrders.validate(id)` rather than as a sourcing data problem on the items.
{% endhint %}

{% hint style="info" %}
System validations are not configured in the workflow template. The template's root `validations` array is reserved in every schema version and does not enable or disable anything today — see [Workflow Reference → Validations Array](https://docs.durohub.com/library-configuration/change-order-workflow-reference.md#validations-array). The template's schema version only affects which validations run indirectly, through the [change order types](https://docs.durohub.com/library-configuration/change-order-workflow-reference.md#change-order-types) it allows.
{% endhint %}

### Custom Validations

JavaScript-based rules you create to enforce your specific business logic:

* Cost threshold checks
* Part number format validation
* Required approver verification
* Impact assessment requirements
* Custom field dependencies

## Running Validations

Run validations with `changeOrders.validate(id)`. It works on a change order in any status and needs the `change_orders.read` permission. A change order can only be submitted once its latest run has passed (`isValid: true`). Here's how to run validations and interpret the results:

### Basic Validation Query

```graphql
mutation ValidateChangeOrder($changeOrderId: ID!) {
  changeOrders {
    validate(id: $changeOrderId) {
      id
      isValid  # Overall validation result

      validationRun {
        id
        state  # PASS, FAIL, or IN_PROGRESS
        summary {
          passCount
          failCount
          warningCount
        }

        results(pagination: { first: 50 }) {
          edges {
            node {
              name
              state
              errorMessage
            }
          }
        }
      }
    }
  }
}
```

{% hint style="info" %}
**Validation can finish after `validate` returns.** In some libraries `validate` queues the run and returns at once with `isValid: false` and a run whose `state` is `IN_PROGRESS`. When that happens, poll the change order's `latestValidationRun` until its `state` is `PASS` or `FAIL`, then read `isValid`. Code written this way also works where `validate` returns the finished run.
{% endhint %}

### Example Response

```json
{
  "data": {
    "changeOrders": {
      "validate": {
        "id": "123e4567-e89b-12d3-a456-426614174000",
        "isValid": false,
        "validationRun": {
          "id": "987fcdeb-51a2-43d1-9876-543210fedcba",
          "state": "FAIL",
          "summary": {
            "passCount": 8,
            "failCount": 2,
            "warningCount": 1
          },
          "results": {
            "edges": [
              {
                "node": {
                  "name": "Items must not exist in other OPEN Change Orders",
                  "state": "FAIL",
                  "errorMessage": "Items already exist in other change orders: CO-2024-001"
                }
              }
            ]
          }
        }
      }
    }
  }
}
```

## Accessing Validation History

Every validation run is stored, allowing you to track how validation results change over time as issues are resolved. A run's `createdBy` is the change order's creator, whoever called `validate`.

### Viewing Latest Validation Results

```graphql
query GetLatestValidation($changeOrderId: ID!) {
  changeOrders {
    get(filter: { ids: [$changeOrderId] }) {
      connection {
        edges {
          node {
            id
            name
            isValid

            latestValidationRun {
              id
              state
              createdAt
              createdBy {
                name
              }

              summary {
                passCount
                failCount
                warningCount
              }

              # Get detailed results with logs
              results(pagination: { first: 100 }) {
                edges {
                  node {
                    name
                    validationType  # SYSTEM or CUSTOM
                    state          # PASS, FAIL, or WARNING
                    onFailure      # ERROR or WARNING
                    errorMessage

                    # Access validation logs for debugging
                    logs {
                      error {
                        message
                      }
                      info {
                        message
                      }
                      all {
                        message
                        type
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
```

### Viewing Historical Validation Runs

Track how validation results have changed over time:

```graphql
query GetValidationHistory($changeOrderId: ID!) {
  changeOrders {
    get(filter: { ids: [$changeOrderId] }) {
      connection {
        edges {
          node {
            id

            # Get all historical validation runs
            validationRuns(pagination: { first: 10 }) {
              edges {
                node {
                  id
                  collectionId
                  state
                  createdAt
                  createdBy {
                    name
                  }

                  summary {
                    passCount
                    failCount
                    warningCount
                  }

                  # Can drill into specific failed validations
                  results(pagination: { first: 100 }) {
                    edges {
                      node {
                        name
                        state
                        errorMessage
                      }
                    }
                  }
                }
              }
              totalCount
            }
          }
        }
      }
    }
  }
}
```

## Understanding Validation Results

Each validation result provides detailed information to help you understand and resolve issues:

### Validation States

* **PASS**: The validation succeeded without issues
* **FAIL**: The validation failed and must be resolved
* **WARNING**: The validation found potential issues that should be reviewed

### OnFailure Behavior

Whether a result blocks submission depends on its `state` and its `onFailure` together:

* A **`FAIL`** result always fails the run and blocks submission, whatever its `onFailure`.
* A **`WARNING`** result fails the run only when its `onFailure` is **`ERROR`**. With `onFailure: WARNING` it alerts reviewers but does not block.
* A **`PASS`** result never blocks.

For example, the [primary source validation](#primary-source-required) reports `onFailure: WARNING` but blocks in `error` mode, because it returns `FAIL`.

### Validation Logs

Each validation generates detailed logs that help with debugging:

```graphql
logs {
  # Informational messages about validation execution
  info {
    message
  }

  # Warnings about potential issues
  warn {
    message
  }

  # Error details when validation fails
  error {
    message
  }

  # All logs in chronological order
  all {
    message
    type  # "info", "warn", "error", or "log"
  }
}
```

## Working with Custom Validations

Custom validations allow you to implement organization-specific business rules. When a custom validation runs, you can access both the validation result and the underlying rule definition:

```graphql
query GetCustomValidationDetails($changeOrderId: ID!) {
  changeOrders {
    get(filter: { ids: [$changeOrderId] }) {
      connection {
        edges {
          node {
            latestValidationRun {
              results(pagination: { first: 50 }) {
                edges {
                  node {
                    name
                    validationType
                    state
                    errorMessage

                    # Only populated for CUSTOM validations
                    validationRule {
                      id
                      name
                      type
                      version
                      code  # The JavaScript validation code
                      library {
                        id
                        name
                      }
                    }

                    # Debug custom validation execution
                    logs {
                      all {
                        message
                        type
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
```

## Practical Examples

### Example 1: Check Only Failed Validations

When debugging validation failures, focus on just the problems:

```graphql
query GetFailedValidations($changeOrderId: ID!) {
  changeOrders {
    get(filter: { ids: [$changeOrderId] }) {
      connection {
        edges {
          node {
            id
            name
            isValid

            latestValidationRun {
              state
              summary {
                failCount
                warningCount
              }

              # Fetch all results, then filter client-side
              results(pagination: { first: 100 }) {
                edges {
                  node {
                    name
                    state
                    errorMessage
                    logs {
                      error {
                        message
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
```

Then filter the results in your application code:

```javascript
const failedValidations = data.changeOrders.get.connection.edges[0]
  .node.latestValidationRun.results.edges
  .filter(edge => edge.node.state === 'FAIL' || edge.node.state === 'WARNING');
```

### Example 2: Monitor Validation Progress

Track validation improvements over multiple runs:

```graphql
query CompareValidationRuns($changeOrderId: ID!) {
  changeOrders {
    get(filter: { ids: [$changeOrderId] }) {
      connection {
        edges {
          node {
            # Current state
            latestValidationRun {
              createdAt
              summary {
                passCount
                failCount
                warningCount
              }
            }

            # Historical comparison
            validationRuns(pagination: { first: 5 }) {
              edges {
                node {
                  createdAt
                  summary {
                    passCount
                    failCount
                    warningCount
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
```

### Example 3: Validation Integration Workflow

Here's a complete workflow for integrating validations into your change order process:

```javascript
// 1. Create or update a change order
const changeOrderId = await createChangeOrder(changeOrderData);

// 2. Run validations, and wait for the run to finish if it was queued
let validationResult = await runValidation(changeOrderId);
while (validationResult.validationRun.state === 'IN_PROGRESS') {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  validationResult = await getLatestValidationRun(changeOrderId); // isValid + latestValidationRun
}

// 3. Check if valid
if (!validationResult.isValid) {
  // 4. Get detailed failure information
  const failures = validationResult.validationRun.results.edges
    .filter(edge => edge.node.state !== 'PASS')
    .map(edge => ({
      name: edge.node.name,
      error: edge.node.errorMessage,
      severity: edge.node.onFailure
    }));

  // 5. Display failures to user
  displayValidationErrors(failures);

  // 6. Allow user to fix issues
  await promptUserToResolveIssues(failures);

  // 7. Re-run validations after fixes (wait for IN_PROGRESS runs as in step 2)
  const retryResult = await runValidation(changeOrderId);

  if (retryResult.isValid) {
    console.log('All validations passed!');
  }
}

// 8. Proceed with approval workflow only if valid
if (validationResult.isValid) {
  await submitForApproval(changeOrderId);
}
```

To try a single custom rule against a change order without recording a run, use `validations.test(id, changeOrderId)`; see [Authoring Custom Validations → Testing a Validation Rule](https://docs.durohub.com/library-configuration/authoring-custom-validations.md#testing-a-validation-rule).

## Best Practices

### 1. Run Validations Early and Often

Don't wait until the approval stage to run validations. Run them:

* After initial change order creation
* After any significant updates
* Before submitting for approval
* After resolving validation failures

### 2. Provide Clear Error Messages

When creating custom validations, ensure error messages are actionable:

* ✅ Good: "Part number ABC-123 must have an associated drawing document"
* ❌ Avoid: "Validation failed"

### 3. Use Warnings Appropriately

Reserve warnings for issues that should be reviewed but don't necessarily block progress:

* Missing optional documentation
* Unusual but acceptable values
* Recommendations for best practices

### 4. Monitor Validation Trends

Track validation patterns across change orders to identify:

* Common failure points in your process
* Training opportunities for users
* Potential system improvements

### 5. Leverage Validation Logs

Use the detailed logs to:

* Debug custom validation logic
* Understand validation execution flow
* Provide context to users about failures

## Troubleshooting

### Common Issues

#### Validation Runs But Shows No Results

Ensure you're requesting the results field with proper pagination:

```graphql
validationRun {
  results(pagination: { first: 100 }) {  # Don't forget pagination
    edges {
      node {
        name
        state
      }
    }
  }
}
```

#### Custom Validation Not Running

Every active custom rule in the library runs on every change order in that library; there are no per-rule conditions. Verify that:

* The validation rule is active (`isActive: true`) in the change order's library
* The rule's `type` is `custom`
* The rule's code compiles and assigns `exports.validate`. A rule that does not shows up as a `FAIL` result with `Failed to execute validation: Request failed with status code 500`

#### Inconsistent Validation Results

Check for:

* Data changes between validation runs
* Updates to validation rules
* Library settings that change built-in checks, such as the [primary source](#primary-source-required) mode

## Next Steps

1. Review your organization's validation requirements
2. Implement custom validations for your specific needs
3. Integrate validation checks into your change order workflow
4. Monitor validation metrics to improve your process

For a complete guide to writing custom validation rules — including the payload structure, attribute access patterns, and practical examples — see [Authoring Custom Validations](https://docs.durohub.com/library-configuration/authoring-custom-validations.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.durohub.com/library-configuration/change-order-validations.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
