Skip to content

Home

DecisionTracker

DecisionTracker is a Python library for writing explainable, traceable, and auditable Python programs.

Using monadic patterns, the library provides the DecisionTracker syntax for writing logic and math operations and control flow. Through this syntax, it allows one or more trees of expressions to be built up under the hood. A tree represents some code paths, math, and logic of the program. Each tree can be evaluated to a final value, equivalent to obtaining one of the outputs of the program if it had been written using vanilla Python syntax instead of DecisionTracker syntax.

In addition, the tree can be simplified to represent only the logic and math of the code path taken to arrive at the tree’s final value. This simplified tree can be flattened to a list of Evaluated Expressions, which can be stored in dedicated database tables. This allows program executions and outputs to be explained, traced, and audited at a level of thoroughness and ease which traditional logging cannot provide.

Furthermore, the library is accompanied by the DecisionTracker Grafana panel, allowing the simplified tree to be reconstructed from the Evaluated Expressions stored in the database, and then viewed interactively.

Note

DecisionTracker does not need you to set up an additional database or service. It is intended for internal use by development and QA teams with existing tech stacks. DecisionTracker is intended to use your existing relational database and, optionally, your existing Grafana instance.

The following diagram illustrates the end-to-end flow:

  1. The logic, math, and code paths of a Python program are written in DecisionTracker syntax. The output expression is actually a tree of expressions. The value property computes its final value. The to_db method converts the tree to a simplified tree of Evaluated Expressions and inserts them into your database along with some metadata.

  2. The Evaluated Expressions and their metadata are stored in evaluated_expression, evaluated_expression_association, and evaluated_expression_metadata tables in your relational database.

  3. Evaluated Expressions are queried from your database. The DecisionTracker Grafana panel reconstructs the simplified tree from the Evaluated Expressions and allows them to be viewed interactively.

DecisionTracker syntax

DecisionTracker syntax is a re-implementation of a subset of Python syntax, in Python syntax, in order to support DecisionTracker’s features. The subset of Python syntax that is supported represents the kind of code expressions that can be stored in a database and for which DecisionTracker offers explainability and traceability.

Numeric expressions

In DecisionTracker syntax, numeric expressions are based on the Numeric class:

Regular Python syntax
a, b, c, d, e = 0, 1, 2, 3, 4
(a + b - c) * d / e
DecisionTracker Python syntax
Numeric(a=0).plus(b=1).minus(c=2).times(d=3).divided_by(e=4)

Note

Just as in regular Python, use of ints and floats are interchangeable in the Numeric class. Performing a binary operation (e.g., addition) between two ints returns an int, performing a binary operation between two floats returns a float, and performing a binary operation between an int and a float returns a float. Division is the exception, which always returns a float.

DecisionTracker syntax is evaluated from left to right. If we wanted to change the order of operations, we would instead write:

Regular Python syntax
a, b, c, d, e = 0, 1, 2, 3, 4
a + b - c * d / e
DecisionTracker Python syntax
Int(Int(a=0).plus(b=1).minus(c=2)).times(d=3).divided_by(e=4)

A numeric expression can be converted to Evaluated Expressions, which can be seen in its string representation:

>>> Int(Int(a=0).plus(b=1).minus(c=2)).times(d=3).divided_by(e=4)
-0.75 because ((((a := 0) + (b := 1)) - (c := 2)) * (d := 3)) / (e := 4)

Note

Nested addition operations, or nested multiplication operations, will be flattened, while maintaining the order of the operands and the final value.

Comparisons

Comparisons of numeric expressions can be written as follows. Comparisons return Bools.

Regular Python syntax
a == b
a != b
a > b
a >= b
a < b
a <= b
DecisionTracker Python syntax
Numeric(a).eq(b)
Numeric(a).neq(b)
Numeric(a).gt(b)
Numeric(a).gte(b)
Numeric(a).lt(b)
Numeric(a).lte(b)

For example:

>>> Numeric(a=4).gt(b=2)
True because (a := 4) > (b := 2)

However, when a comparison evaluates to False, the comparison gets flipped in its Evaluated Expression. For example:

>>> Numeric(a=2).gt(b=4)
False because (a := 2) <= (b := 4)

Bool expressions

In DecisionTracker syntax, bool expressions are based on the Bool class:

Regular Python syntax
x, y, z = True, True, False
(x or y) and not z
DecisionTracker Python syntax
Bool(x=True).or_(y=True).and_(Not(z=False))

Again, DecisionTracker syntax is evaluated from left to right. If we wanted to change the order of operations, we would instead write:

Regular Python syntax
x, y, z = True, True, False
x or y and not z
DecisionTracker Python syntax
Bool(x=True).or_(Bool(y=True).and(Not(z=False)))

Just like a numeric expression, a bool expression can be converted to Evaluated Expressions, which can be seen in its string representation:

>>> Bool(x=True).or_(y=True).or_(z=True))
True because (x := True) or (y := True) or (z := True)
>>> Bool(x=True).and_(y=True).and_(z=True)
True because (x := True) and (y := True) and (z := True)

Note

Nested “or” operations, or nested “and” operations, will be flattened, while maintaining the order of the operands and the final value.

However, when the following get converted to Evaluated Expressions, things look a bit different. Click on the icons to understand each case. These are examples of how Evaluated Expressions are not designed to represent the entire program, but to explain why it output certain values.

  • >>> Bool(x=False).or_(y=True).or_(z=True)
    True because (y := True) or (z := True) # (1)!
    

    1. Why does this Evaluated Expression omit x?
      Because x did not contribute to the final value being True.
  • >>> Bool(x=False).or_(y=False).or_(z=False)
    False because (x := False) and (y := False) and (z := False) # (1)!
    

    1. Why has “or” been replaced with “and”?
      Because the final value could be False only if all the inputs were False.
  • >>> Bool(x=True).and_(y=False).and_(z=False)
    False because (y := False) or (z := False) # (1)!
    

    1. Why does this Evaluated Expression omit x?
      Because x did not contribute to the final value being False.

      Why has “and” been replaced with “or”?
      Because the final value could be False if any of the inputs were False.

  • >>> str(Not(x=True))
    False because (x := True) # (1)!
    >>> str(Not(x=False))
    True because (x := False) # (2)!
    

    1. Why do these Evaluated Expressions not include the “not” operator?
      Because, just like above, the operator is not considered to be causing the final value.
    2. Why do these Evaluated Expressions not include the “not” operator?
      Because, just like above, the operator is not considered to be causing the final value.

DecisionTracker supports alternate syntaxes for convenience or to suit user preferences:

  • Bool(x).and_(y).and_(z)) can alternately be written as Bool(x).and_(y, z).
  • Bool(x).or_(Bool(y).and_(z)) can alternately be written as Bool(x).or_(y, z).

If-elif-else blocks

Regular Python syntax
if a:
    return a1
elif b
    return b1
else:
    return c1
DecisionTracker Python syntax
return If(a).then(
    a1
).elif_(b).then(
    b1
).else_(
    c1
)

Obviously, you can have as many .elif_(...).then(...) cases as you wish (including none). However, unlike in regular Python syntax, a final .else_(...) is always required.

Ternary operators

Ternary operator expressions can be written as follows:

Regular Python syntax
a, b, c = 1, True, 2
a if b else c
DecisionTracker Python syntax
Int(a=1).if_(b=True).else_(c=2)

Ternary operator expressions can be chained, but like this:

a if b else c if d else e
Int(a).if_(b).else_(c.if_(d).else_(e))

Not like the following (which checks d before b and is likely not what is intended); simply keep in mind that DecisionTracker syntax is evaluated from left to right.

(a if b else c) if d else e
Int(a).if_(b).else_(c).if_(d).else_(e)

Dict lookups

Dictionary lookups can be written as follows:

Regular Python syntax
{
    "a": a,
    "b": b,
}[x]
DecisionTracker Python syntax
Lookup(
    {
        "a": a,
        "b": b,
    },
    x,
)
Regular Python syntax
{
    "a": a,
    "b": b,
}.get(x, c)
DecisionTracker Python syntax
UncertainLookup(
    {
        "a": a,
        "b": b,
    },
    x,
    c,
)
Regular Python syntax
{
    "a": a,
    "b": b,
}.get(x)
DecisionTracker Python syntax
val = UncertainLookup(
    {
        "a": a,
        "b": b,
    },
    x,
)

The return value of .get(x) should be checked to not be None before being used. Similarly, IsNotNull(val) should be checked before using val — that is, using Numeric(val) if its possible values are numeric, Bool(val) if boolean, and so on.

Nullable expressions

In Python, None indicates the absence of a value. A variable of a certain type T becomes an optional variable when of type Optional[T] or, equivalently, of type T | None. The variable can only be treated as type T after checking that the variable is not None.

In DecisionTracker syntax, the term nullable is used instead of optional. A DecisionTracker expression is nullable if its .value is of type T | None instead of just T. A nullable expression can be created from the Nullable class.

For example, say your program has an input x, retrieved by function get_x with the following signature.

def get_x() -> int | None: ...

In DecisionTracker syntax, this input must be wrapped with Nullable:

Regular Python syntax
x = get_x() # (1)!
  1. x has type int | None.
DecisionTracker Python syntax
x = Nullable(get_x()) # (1)!
  1. x has type Nullable[int].

Nullable allows checking whether the nullable expression is null (by checking its properties .is_null or .is_not_null). This is useful, for example, to provide a fallback value:

Regular Python syntax
y = x if x is not None else 0 # (1)!
  1. y has type int, not int | None, and Python’s type checker knows this.
DecisionTracker Python syntax
y = Numeric.from_(x).if_(x.is_not_null).else(0) # (1)!
  1. y has type Numeric, not Nullable[int], and we had to explicitly establish that fact by starting our DecisionTracker expression with Numeric.

    Numeric.from_(x) is analogous to typing.cast(int, x).

Sometimes you want to use a variable (e.g., in a calculation) and, if it is null, ‘persist’ the null value:

y = x * 2 if x is not None else None # (1)!
  1. y has type int | None, just like x, and Python’s type checker knows this.
y = Nullable(Numeric.from_(x).times(2)).if_(x.is_not_null).else_(None) # (1)!
  1. y has type Nullable[int], just like x, and we had to explicitly establish that fact by starting our DecisionTracker expression with Nullable.

DecisionTracker expression

Property value

Compute and return the DecisionTracker expression’s final value. The value of a Bool expression, for example, is a raw bool.

Method to_db

Convert the DecisionTracker expression and its child expressions to a simplified tree of Evaluated Expressions, and then inserts them into dedicated database tables.

Arguments:

  • engine: An SQLAlchemy Engine object with which to insert the Evaluated Expressions.

  • metadata: Key-value pairs of metadata for the DecisionTracker expression. Keys correspond to evaluated_expression_metadata table columns (e.g., service_id, timestamp).

  • db_schema: Name of the database schema containing the tables. Defaults to “decision_tracker”.

Storage of Evaluated Expressions in your database

DecisionTracker requires dedicated tables in your relational database (e.g., Postgres), potentially in a dedicated schema.

  • The evaluated_expression table stores Evaluated Expressions (naturally).

  • The evaluated_expression_association table stores the relationships between the Evaluated Expressions. Usually, this is a one-to-many (parent-children) relationship. However, because a child expression can be used and reused in more than one parent expression, this has been generalized to a many-to-many relationship which requires such an association table.

  • The evaluated_expression_metadata table stores arbitrary, user-defined metadata for each root Evaluated Expression, specified when calling to_db.

The following SQL script can be executed to create the tables. A single, dedicated schema called "decision_tracker" is recommended, especially if you plan on integrating multiple services with it. Adding evaluated_expression_metadata columns, such as a service_id and timestamp, is strongly recommended.

CREATE TABLE decision_tracker.evaluated_expression (
    id UUID PRIMARY KEY,
    name TEXT NULL,
    value JSONB,
    operator TEXT NOT NULL
);

CREATE TABLE decision_tracker.evaluated_expression_association (
    child_id PRIMARY KEY UUID,
    parent_id PRIMARY KEY UUID,

    CONSTRAINT FOREIGN KEY child_id REFERENCES decision_tracker.evaluated_expression.id,
    CONSTRAINT FOREIGN KEY parent_id REFERENCES decision_tracker.evaluated_expression.id
);

CREATE TABLE decision_tracker.evaluated_expression_metadata (
    evaluated_expression_id PRIMARY KEY UUID,
    <your metadata columns here>

    CONSTRAINT FOREIGN KEY evaluated_expression_id REFERENCES decision_tracker.evaluated_expression.id,
);

Interactive viewing using the Grafana panel

Refer to the documentation of the DecisionTracker Grafana panel.