Home
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:
-
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
valueproperty computes its final value. Theto_dbmethod converts the tree to a simplified tree of Evaluated Expressions and inserts them into your database along with somemetadata. -
The Evaluated Expressions and their metadata are stored in
evaluated_expression,evaluated_expression_association, andevaluated_expression_metadatatables in your relational database. -
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:
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:
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.
For example:
However, when a comparison evaluates to False, the comparison gets flipped in its Evaluated Expression. For example:
Bool expressions
In DecisionTracker syntax, bool expressions are based on the Bool class:
Again, DecisionTracker syntax is evaluated from left to right. If we wanted to change the order of operations, we would instead write:
Just like a numeric expression, a bool expression can be converted to Evaluated Expressions, which can be seen in its string representation:
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.
-
- Why does this Evaluated Expression omit
x?
Becausexdid not contribute to the final value beingTrue.
- Why does this Evaluated Expression omit
-
>>> Bool(x=False).or_(y=False).or_(z=False) False because (x := False) and (y := False) and (z := False) # (1)!- Why has “or” been replaced with “and”?
Because the final value could beFalseonly if all the inputs wereFalse.
- Why has “or” been replaced with “and”?
-
- Why does this Evaluated Expression omit
x?
Becausexdid not contribute to the final value beingFalse.Why has “and” been replaced with “or”?
Because the final value could beFalseif any of the inputs wereFalse.
- Why does this Evaluated Expression omit
-
>>> str(Not(x=True)) False because (x := True) # (1)! >>> str(Not(x=False)) True because (x := False) # (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. - 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.
- Why do these Evaluated Expressions not include the “not” operator?
DecisionTracker supports alternate syntaxes for convenience or to suit user preferences:
Bool(x).and_(y).and_(z))can alternately be written asBool(x).and_(y, z).Bool(x).or_(Bool(y).and_(z))can alternately be written asBool(x).or_(y, z).
If-elif-else blocks
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:
Ternary operator expressions can be chained, but like this:
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.
Dict lookups
Dictionary lookups can be written as follows:
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.
In DecisionTracker syntax, this input must be wrapped with Nullable:
xhas typeint | None.
xhas typeNullable[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:
yhas typeint, notint | None, and Python’s type checker knows this.
yhas typeNumeric, notNullable[int], and we had to explicitly establish that fact by starting our DecisionTracker expression withNumeric.Numeric.from_(x)is analogous totyping.cast(int, x).
Sometimes you want to use a variable (e.g., in a calculation) and, if it is null, ‘persist’ the null value:
yhas typeint | None, just likex, and Python’s type checker knows this.
yhas typeNullable[int], just likex, and we had to explicitly establish that fact by starting our DecisionTracker expression withNullable.
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 SQLAlchemyEngineobject with which to insert the Evaluated Expressions. -
metadata: Key-value pairs of metadata for the DecisionTracker expression. Keys correspond toevaluated_expression_metadatatable 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_expressiontable stores Evaluated Expressions (naturally). -
The
evaluated_expression_associationtable 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_metadatatable stores arbitrary, user-defined metadata for each root Evaluated Expression, specified when callingto_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.