SIGN IN SIGN UP

Patching (#524)

Patching is a mechanism for safely upgrading workflow code. It is an
alternative to [workflow
versioning](https://docs.dbos.dev/python/tutorials/workflow-tutorial#workflow-versioning-and-recovery)
(though they can be used together).

The problem patching solves is "How do I make a breaking change to a
workflow's code but continue execution of long-running workflows that
started on the old code version?" A breaking change is any change in
what steps run or the order in which they run.

To use patching, first enable it in configuration:

```python
config: DBOSConfig = {
    "name": "dbos-starter",
    "system_database_url": os.environ.get("DBOS_SYSTEM_DATABASE_URL"),
    "enable_patching": True,
}
DBOS(config=config)
```

Next, when making a breaking change, use an `if DBOS.patch():`
conditional. `DBOS.patch()` returns `True` for new workflows (those
started after the breaking change) and `False` for old workflows (those
started before the breaking change). Therefore, if `DBOS.patch()` is
true, call the new code, else call the old code.

So let's say our workflow is:

```python
@DBOS.workflow()
def workflow():
  foo()
  bar()
```

We want to replace the call to `foo()` with a call to `baz()`, which is
a breaking change. We can do this safely using a patch:

```python
@DBOS.workflow()
def workflow():
  if DBOS.patch("use-baz"):
    baz()
  else:
    foo()
  bar()
```

Now, new workflows will run `baz()`, while old workflows will safely
recover through `foo()`.

Once all workflows of the pre-patch code version are complete, we can
remove patches from our code. First, we deprecate the patch. This will
safely run workflows containing the patch marker, but will not insert
the patch marker into new workflows:

```python
@DBOS.workflow()
def workflow():
  DBOS.deprecate_patch("use-baz")
  baz()
  bar()
```

Then, when all workflows containing the patch marker are complete, we
can remove the patch entirely and complete the workflow upgrade!

```python
@DBOS.workflow()
def workflow():
  baz()
  bar()
```

If any mistakes happen during the process (a breaking change is not
patched, or a patch is deprecated or removed prematurely), the workflow
will throw a clean `DBOSUnexpectedStepError` pointing to the step where
the problem occurred.

Also, one advanced feature is that if you need to make consecutive
breaking changes to the same code, you can stack patches:

```python
@DBOS.workflow()
def workflow():
  if DBOS.patch("use-qux"):
    qux()
  elif DBOS.patch("use-baz"):
    baz()
  else:
    foo()
  bar()
```
P
Peter Kraft committed
95d0df976f1dbc5fecd9f97a863ba9c7d853ff0e
Parent: 85b8073
Committed by GitHub <noreply@github.com> on 12/8/2025, 6:31:22 PM