You want a simple DSL for computed metrics using Python, on top of time-series database fields. This means:
- Defining Base Fields: Representing the raw data from your database.
- Defining Operations:
+, -, *, /, average, sum, etc.
- Combining Metrics: Operations should return new metric objects, forming a computation tree.
- Tree Visualization: A way to see the structure of the computation.
- DB Field Tracing: Identify all the raw database fields required for a computed metric.
- Evaluation: Compute the actual value given a dictionary of raw data.
We'll achieve this using a class-based approach where each field or operation is an object, and Python's operator overloading (__add__, __sub__, etc.) makes the DSL feel natural.
Core Concepts
Metric Base Class: An abstract base class defining common methods for all metric types (evaluate, to_tree, get_db_fields).
DBField: A leaf node representing a raw field from the database.
Constant: A leaf node for literal numeric values in calculations (e.g., field_x + 10).
- Operation Classes (
Add, Subtract, Multiply, Divide, Average, Sum): Nodes that combine other Metric objects.
- Operator Overloading: Implementing special methods like
__add__ on Metric allows you to write field_a + field_b instead of Add(field_a, field_b).
Implementation
import abc
# --- 1. Base Metric Class ---
class Metric(abc.ABC):
"""
Abstract Base Class for all metric types.
Defines common interface for evaluation, tree representation,
and dependency tracking.
"""
def __init__(self, name=None):
self._name = name
def name(self):
return self._name if self._name else self.__class__.__name__
@abc.abstractmethod
def evaluate(self, data: dict):
"""
Computes the metric's value given a dictionary of raw data.
:param data: A dict where keys are DB field names and values are their time-series points.
:return: The computed metric value.
"""
pass
@abc.abstractmethod
def to_tree(self, indent=0):
"""
Returns a string representation of the computation tree.
:param indent: Current indentation level for visual hierarchy.
:return: String representation.
"""
pass
@abc.abstractmethod
def get_db_fields(self) -> set:
"""
Returns a set of all unique DB field names involved in this metric's computation.
"""
pass
# --- Operator Overloading for DSL ---
# These methods make it possible to use standard Python operators (+, -, *, /)
# on Metric objects, returning new operation Metric objects.
def _wrap_operand(self, other):
"""Helper to ensure the other operand is a Metric object."""
if isinstance(other, Metric):
return other
if isinstance(other, (int, float)):
return Constant(other)
raise TypeError(f"Unsupported operand type for Metric operation: {type(other)}")
def __add__(self, other):
return Add(self, self._wrap_operand(other))
def __radd__(self, other):
return Add(self._wrap_operand(other), self)
def __sub__(self, other):
return Subtract(self, self._wrap_operand(other))
def __rsub__(self, other):
return Subtract(self._wrap_operand(other), self)
def __mul__(self, other):
return Multiply(self, self._wrap_operand(other))
def __rmul__(self, other):
return Multiply(self._wrap_operand(other), self)
def __truediv__(self, other):
return Divide(self, self._wrap_operand(other))
def __rtruediv__(self, other):
return Divide(self._wrap_operand(other), self)
def __repr__(self):
return self.to_tree()
# --- 2. Leaf Nodes (Raw Data & Constants) ---
class DBField(Metric):
"""
Represents a raw field directly from the time-series database.
This is a leaf node in the computation tree.
"""
def __init__(self, field_name: str):
super().__init__(name=field_name)
self.field_name = field_name
def evaluate(self, data: dict):
if self.field_name not in data:
raise ValueError(f"DB field '{self.field_name}' not found in provided data.")
return data[self.field_name]
def to_tree(self, indent=0):
return f"{' ' * indent}DBField: '{self.field_name}'"
def get_db_fields(self) -> set:
return {self.field_name}
class Constant(Metric):
"""
Represents a constant numeric value in a calculation.
This is a leaf node in the computation tree.
"""
def __init__(self, value: (int, float)):
super().__init__(name=f"Constant({value})")
self.value = value
def evaluate(self, data: dict):
return self.value
def to_tree(self, indent=0):
return f"{' ' * indent}Constant: {self.value}"
def get_db_fields(self) -> set:
return set() # Constants don't depend on DB fields
# --- 3. Operation Classes ---
class OperationMetric(Metric):
"""
Base class for metrics that perform an operation on one or more child metrics.
"""
def __init__(self, *operands: Metric, name=None):
if not operands:
raise ValueError("OperationMetric must have at least one operand.")
super().__init__(name=name)
self.operands = operands
def to_tree(self, indent=0):
tree_str = f"{' ' * indent}{self.name()}:\n"
for op in self.operands:
tree_str += op.to_tree(indent + 1) + "\n"
return tree_str.strip() # Remove trailing newline from last operand
def get_db_fields(self) -> set:
fields = set()
for op in self.operands:
fields.update(op.get_db_fields())
return fields
class Add(OperationMetric):
def __init__(self, *operands: Metric):
super().__init__(*operands, name="Add")
def evaluate(self, data: dict):
return sum(op.evaluate(data) for op in self.operands)
class Subtract(OperationMetric):
def __init__(self, op1: Metric, op2: Metric):
super().__init__(op1, op2, name="Subtract")
def evaluate(self, data: dict):
return self.operands[0].evaluate(data) - self.operands[1].evaluate(data)
class Multiply(OperationMetric):
def __init__(self, *operands: Metric):
super().__init__(*operands, name="Multiply")
def evaluate(self, data: dict):
result = 1
for op in self.operands:
result *= op.evaluate(data)
return result
class Divide(OperationMetric):
def __init__(self, op1: Metric, op2: Metric):
super().__init__(op1, op2, name="Divide")
def evaluate(self, data: dict):
numerator = self.operands[0].evaluate(data)
denominator = self.operands[1].evaluate(data)
if denominator == 0:
raise ZeroDivisionError(f"Attempted to divide by zero in {self.name()} operation.")
return numerator / denominator
class Average(OperationMetric):
def __init__(self, *operands: Metric):
super().__init__(*operands, name="Average")
def evaluate(self, data: dict):
values = [op.evaluate(data) for op in self.operands]
if not values:
raise ValueError("Cannot calculate average of no values.")
return sum(values) / len(values)
class Sum(OperationMetric):
def __init__(self, *operands: Metric):
super().__init__(*operands, name="Sum")
def evaluate(self, data: dict):
return sum(op.evaluate(data) for op in self.operands)
# --- 4. Convenience Functions (Optional, but nice for DSL) ---
# These functions act as syntactic sugar, allowing `avg(field_a, field_b)`
# instead of `Average(field_a, field_b)`.
def field(name: str) -> DBField:
return DBField(name)
def constant(value: (int, float)) -> Constant:
return Constant(value)
def avg(*metrics: Metric) -> Average:
return Average(*metrics)
def sum_of(*metrics: Metric) -> Sum:
return Sum(*metrics)
def max_val(*metrics: Metric) -> Metric: # You'd implement a Max class similarly
# For simplicity, let's just use a placeholder here for Max/Min
# You would create a `Max` and `Min` class like Average/Sum
# and adjust the `evaluate` method.
class Max(OperationMetric):
def __init__(self, *operands: Metric):
super().__init__(*operands, name="Max")
def evaluate(self, data: dict):
values = [op.evaluate(data) for op in self.operands]
if not values: raise ValueError("Cannot calculate max of no values.")
return max(values)
return Max(*metrics)
def min_val(*metrics: Metric) -> Metric:
class Min(OperationMetric):
def __init__(self, *operands: Metric):
super().__init__(*operands, name="Min")
def evaluate(self, data: dict):
values = [op.evaluate(data) for op in self.operands]
if not values: raise ValueError("Cannot calculate min of no values.")
return min(values)
return Min(*metrics)
Example Usage
Let's define some database fields and then build complex metrics.
# --- Define your raw DB fields ---
# You would typically define these once in your application setup
cpu_usage = field('sys.cpu.usage')
mem_free = field('sys.mem.free')
network_in_bytes = field('net.bytes.in')
network_out_bytes = field('net.bytes.out')
disk_io_read = field('disk.io.read')
disk_io_write = field('disk.io.write')
error_rate = field('app.errors.rate')
request_count = field('app.requests.count')
response_time = field('app.response.time')
# --- Build Complex Metrics using the DSL ---
# Metric 1: Total Network Traffic (in GB)
total_network_traffic_gb = (network_in_bytes + network_out_bytes) / constant(1024**3)
# Metric 2: Disk IO Utilization (simple sum)
disk_io_utilization = disk_io_read + disk_io_write
# Metric 3: Application Health Score (weighted average, hypothetical)
# (response_time * 0.6) + (error_rate * 0.3) + (100 - cpu_usage * 0.1)
app_health_score = (response_time * 0.6) + (error_rate * 0.3) + (constant(100) - cpu_usage * 0.1)
# Metric 4: Average CPU and Memory Usage
avg_system_usage = avg(cpu_usage, mem_free)
# Metric 5: Combined Network & Disk metric
combined_usage = total_network_traffic_gb + disk_io_utilization
# Metric 6: Error Rate Per Request (example of combining previous metrics)
error_rate_per_request = error_rate / request_count
# Metric 7: More complex aggregation: Max of avg system usage and response time
max_performance_metric = max_val(avg_system_usage, response_time)
# --- Demonstrate Functionality ---
print("--- Metric: Total Network Traffic (GB) ---")
print(total_network_traffic_gb.to_tree())
print(f"Required DB Fields: {total_network_traffic_gb.get_db_fields()}")
sample_data_1 = {
'net.bytes.in': 500 * (1024**2), # 500 MB
'net.bytes.out': 700 * (1024**2) # 700 MB
}
print(f"Evaluated value with sample data: {total_network_traffic_gb.evaluate(sample_data_1):.2f} GB\n")
print("\n--- Metric: Application Health Score ---")
print(app_health_score.to_tree())
print(f"Required DB Fields: {app_health_score.get_db_fields()}")
sample_data_2 = {
'app.response.time': 150,
'app.errors.rate': 0.05,
'sys.cpu.usage': 75
}
print(f"Evaluated value with sample data: {app_health_score.evaluate(sample_data_2):.2f}\n")
print("\n--- Metric: Combined Network & Disk Usage ---")
print(combined_usage.to_tree())
print(f"Required DB Fields: {combined_usage.get_db_fields()}")
sample_data_3 = {
'net.bytes.in': 100 * (1024**3), # 100 GB
'net.bytes.out': 50 * (1024**3), # 50 GB
'disk.io.read': 1000,
'disk.io.write': 500
}
print(f"Evaluated value with sample data: {combined_usage.evaluate(sample_data_3):.2f}\n")
print("\n--- Metric: Max Performance Metric ---")
print(max_performance_metric.to_tree())
print(f"Required DB Fields: {max_performance_metric.get_db_fields()}")
sample_data_4 = {
'sys.cpu.usage': 60,
'sys.mem.free': 20,
'app.response.time': 300
}
print(f"Evaluated value with sample data: {max_performance_metric.evaluate(sample_data_4):.2f}\n")
# --- Example of Missing Data Handling ---
print("\n--- Example: Missing Data ---")
try:
total_network_traffic_gb.evaluate({'net.bytes.in': 100}) # 'net.bytes.out' is missing
except ValueError as e:
print(f"Error evaluating: {e}")
# --- Example of Division by Zero ---
print("\n--- Example: Division by Zero ---")
zero_divisor_metric = field('numerator') / field('denominator')
try:
zero_divisor_metric.evaluate({'numerator': 10, 'denominator': 0})
except ZeroDivisionError as e:
print(f"Error evaluating: {e}")
Explanation
-
Metric (Abstract Base Class):
- It defines the contract for all metric types:
evaluate, to_tree, and get_db_fields.
- Crucially, it implements Python's "dunder" (double underscore) methods like
__add__, __sub__, __mul__, __truediv__, and their "reverse" counterparts (__radd__, etc.).
- When you write
cpu_usage + mem_free, cpu_usage.__add__(mem_free) is called. This method doesn't perform the calculation directly; instead, it returns a new Add metric object, which itself holds cpu_usage and mem_free as its operands. This is how the computation tree is built.
- The
_wrap_operand helper automatically turns numbers (like 1024**3) into Constant metric objects, ensuring everything in the tree is a Metric subclass.
-
DBField:
- This is the simplest
Metric. It just holds the name of a database field.
evaluate: Looks up its field_name in the provided data dictionary.
to_tree: Just prints its name.
get_db_fields: Returns a set containing only its own name, as it's a direct dependency.
-
Constant:
- Similar to
DBField but holds a static numeric value.
get_db_fields returns an empty set as it has no DB dependencies.
-
OperationMetric (Base for operations):
- A base class for all operations (Add, Subtract, etc.) that take other metrics as operands.
- It stores
self.operands, which is a tuple of the Metric objects it's operating on.
to_tree: Recursively calls to_tree on its operands, adding indentation for visual hierarchy.
get_db_fields: Recursively calls get_db_fields on all its operands and combines the results using set.union, ensuring all unique underlying DB fields are captured.
-
Specific Operation Classes (, , , , , ):
How it builds the tree:
When you write something like (network_in_bytes + network_out_bytes) / constant(1024**3):
network_in_bytes + network_out_bytes: Calls DBField.__add__(network_out_bytes). This returns an Add object where operands are (network_in_bytes, network_out_bytes). Let's call this metric_sum.
metric_sum / constant(1024**3): Calls Add.__truediv__(Constant(1024**3)). This returns a Divide object where operands are (metric_sum, Constant(1024**3)). This Divide object is your final total_network_traffic_gb metric.
When you call total_network_traffic_gb.to_tree(), it starts from the Divide object, which then calls to_tree on metric_sum (the Add object), which then calls to_tree on network_in_bytes and network_out_bytes. This recursive traversal generates the tree structure.
Similarly, get_db_fields() and evaluate() recursively traverse the tree from top to bottom or bottom to top, respectively, to gather fields or compute values.
This structure provides a clean, Pythonic, and extensible way to define complex computed metrics while retaining full introspection into their composition and dependencies.