Laboratory: Sure-footed Refactoring with Experiments

1.0.2 · active · verified Thu Apr 16

Laboratory is a Python library (version 1.0.2) that enables confident refactoring of critical code paths by running 'experiments' in production. Inspired by GitHub's Scientist, it executes new code (candidate) alongside existing code (control) in a randomized order, compares return values, records timing, and logs exceptions, providing a feedback loop for verification. The library is stable and addresses a timeless engineering problem, though its release cadence is slow.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up and run a basic experiment. You define a 'control' function (your existing code) and a 'candidate' function (your new code). The `Experiment` class runs both, returning the control's result. Under the hood, it compares results, records performance, and logs exceptions from the candidate, which can then be published to a metrics system (not shown in this basic example).

import laboratory
import time

def old_function(value):
    time.sleep(0.01)
    return value * 2

def new_function(value):
    # Simulate a refactored version, possibly faster or different
    time.sleep(0.005)
    return value + value

experiment = laboratory.Experiment()
experiment.control(old_function, args=(5,))
experiment.candidate(new_function, args=(5,))

# Conduct the experiment. By default, it returns the control's value.
# Candidate's return value, timing, and exceptions are recorded internally.
result = experiment.conduct()

print(f"Experiment conducted. Control result: {result}")

# To access detailed observation data (requires a publisher to be configured)
# For demonstration, we'll manually inspect the internal result, normally
# this would be sent to a metrics/logging system.
# For a real scenario, you'd typically subclass Experiment to implement
# a publisher. Example below is illustrative of what data is collected.
# print(f"Control value: {experiment._observations[0].value}") # Not a public API, for illustration
# print(f"Candidate value: {experiment._observations[1].value}") # Not a public API, for illustration
# print(f"Mismatched: {experiment._result.mismatched}") # Not a public API, for illustration

view raw JSON →