## 🔧 Field Note 06: Implementing the Bitemporal Engine ### Building two clocks and the payout routine *By Lund Consulting | Der Maschinenraum* In our last Field Note, we saw how a single-timeline architecture creates financial amnesia during backdated updates. A native bitemporal engine fixes this cleanly. We do not need complex retroactive conditional logic. The value lies in radical architectural simplicity: we move the temporal tracking out of our code and directly into our data schema. The implementation requires three distinct, manageable layers. ## 1. Layer 1: The Two Clocks (Dual Timelines in Every Table) The core mechanism is straightforward. We don't write a custom retro engine. Instead, we add two specific date columns to both our tables `HR_Data` and `Payout_Ledger`. Every row tracks two distinct timelines: - **Effective Date:** The timeline where the fact becomes valid in the real world (or the payroll period it applies to). - **Knowledge Date:** The exact day the system actually recorded the row. When a backdated change is entered on May 15th, we do not overwrite any data. We simply append the new fact to our records. Here is exactly how both tables look on May 15th, right before the engine runs: *Table A: HR_Data* | Employee | Attribute | Value | Effective Date | Knowledge Date | | -------- | ------------- | ------------- | -------------- | -------------- | | Marcus | Leaver_Status | Normal Leaver | 2026-03-31 | 2026-03-01 | | Marcus | Leaver_Status | Good Leaver | 2026-03-31 | 2026-05-15 | *Table B: Payout_Ledger* *Assuming the system calculates monthly payouts 5 days before end of month.* | Employee | Payout Amount | Effective Date (Payout for) | Knowledge Date (Calculated on) | Comment | | -------- | ------------- | --------------------------- | ------------------------------ | ---------------------------------------- | | Marcus | $0 | 2026-03-31 | 2026-03-26 | Normal Leaver, receiving no annual bonus | | Jane | $5,000 | 2026-03-31 | 2026-03-26 | Not a leaver, monthly salary | | Jane | $50,000 | 2026-03-31 | 2026-03-26 | Not a leaver, annual bonus | | Jane | $5,000 | 2026-04-30 | 2026-04-25 | Not a leaver, monthly salary | --- ## 2. Layer 2: The Lens (The Parameterized Calculation) Because our tables natively track both timelines, your core business math remains entirely time-agnostic. Your calculation logic does not need to know whether it is executing a standard monthly run or a historical correction. Instead, the calculation engine treats time purely as a pair of query parameters. It splits the two dates to perform a surgical point-in-time calculation: - `target_effective_date` pins the engine to a specific historical payroll month, ensuring we evaluate the financial data and rules valid for that period. - `target_knowledge_date` establishes the system's threshold of knowledge. Because we are dealing with backdated changes, this date sits later than the effective date—meaning the engine can surgically calculate the past using our present-day knowledge. ```python title:calculation_engine.py def calculate_payout(employee_id, target_effective_date, target_knowledge_date): # NOTE: Simplified for illustration. In production, this function # routes all compensation types (Base Salary, Commissions, Leaver Status). # We also omit the active-employee fallback and param-passing for brevity. # 1. Use the KNOWLEDGE date parameters to capture backdated states status_query = db.query(""" SELECT value FROM HR_Data WHERE employee = :employee_id AND effective_date <= :target_effective_date AND knowledge_date <= :target_knowledge_date AND attribute = 'Leaver_Status' ORDER BY knowledge_date DESC, effective_date DESC LIMIT 1 """, employee_id=employee_id, target_effective_date=target_effective_date, target_knowledge_date=target_knowledge_date) # Extract the scalar string value from the database query result status = status_query.scalar() if status == "Normal Leaver": return 0 elif status == "Good Leaver": return execute_good_leaver_formulas(employee_id, target_effective_date) ``` **Breaking Down the Mechanics** When the system processes a backdated change, it evaluates the target historical windows using this function. As an example of how these parameters intersect for a single historical period (like Marcus's March window), the system feeds this function a split set of coordinates where the knowledge date is explicitly later than the effective date: - `target_effective_date` = "2026-03-31" (The past period we are calculating) - `target_knowledge_date` = "2026-05-15" (Our present-day knowledge cutoff) This parameter mapping solves the relationship beautifully. The query looks back at the March 31st payroll period, but filters the data through our modern May 15th state of knowledge. Because the database can see our May entry, it uncovers the updated Good Leaver status. The engine then seamlessly calculates the March bonus utilizing our latest, real-world knowledge of Marcus's true eligibility. --- ## 3. Layer 3: The Gears (The Payout Routine) The Payout Routine is the automated script executed at the end of every payout cycle. As a first step, it isolates any employee and payroll period where our HR knowledge is newer than the latest entry recorded in our `Payout_Ledger`. To understand how this works, consider our concrete example: - On May 15, 2026, HR records a retroactive change for Marcus dating back to March. - Meanwhile, our `Payout_Ledger` contains closed records for March 31 and April 30 recorded back in March and April. The database query detects that Marcus's HR knowledge date (2026-05-15) is newer than his March ledger entry (2026-03-26). It immediately flags Marcus for March 31 as a correction queue item, dragging along what was previously paid (`pay_then` = $0). With the target coordinates established, Python loops through these corrections in a single pass. It runs the math engine, checks the delta, and writes the correction. ```python title:payout_routine.py # Today's run date is only used to timestamp our current execution context current_run_date = "2026-05-26" # 1. FETCH ONLY MISMATCHED COORDINATES WHERE HR DATA IS NEWER THAN THE LEDGER corrections = db.query(""" SELECT DISTINCT employee, effective_date AS target_date, ( SELECT COALESCE(SUM(payout_amount), 0) FROM Payout_Ledger WHERE employee = HR_Data.employee AND payout_for = HR_Data.effective_date ) AS pay_then FROM HR_Data WHERE knowledge_date > COALESCE( ( SELECT MAX(knowledge_date) FROM Payout_Ledger WHERE employee = HR_Data.employee AND payout_for = HR_Data.effective_date ), '1970-01-01' ) """) # 2. EVALUATE MATH AND WRITE RECONCILIATIONS IN A SINGLE PASS for item in corrections: # Calculate present truth as of today's run date pay_now = calculate_payout( employee_id=item.employee, target_effective_date=item.target_date, target_knowledge_date=current_run_date ) # Calculate the correction delta delta = pay_now - item.pay_then # Write to ledger only if there is a real cash difference if delta != 0: db.execute(""" INSERT INTO Payout_Ledger (employee, payout_amount, payout_for, knowledge_date, comment) VALUES (:emp, :delta, :target_date, :calc_on, 'Backdated bonus adjustment') """, emp=item.employee, delta=delta, target_date=item.target_date, calc_on=current_run_date) ``` --- ## 4. The Self-Cleaning Loop Look at how elegantly this loop handles the timeline. When the loop evaluates the March 31st cycle, it checks the anchor (`pay_then` = $0), runs the formulas via Layer 2 (`pay_now` = $50,000), and executes our universal subtraction formula: `Δ = Pay(Now) - Pay(Then)` `Δ = $50,000 - $0 = $50,000` It writes the correction to the ledger with today's date (2026-05-26). When the engine runs next month in June, the SQL query checks Marcus again. It compares his HR knowledge date (2026-05-15) against his new ledger knowledge date (2026-05-26). Since the HR knowledge is no longer newer than the ledger knowledge, Marcus is automatically filtered out by the database query. The final result is appended directly into the payout ledger: *Table B: Payout_Ledger (Updated)* *Assuming the system calculates monthly payouts 5 days before end of month.* | Employee | Payout Amount | Effective Date (Payout for) | Knowledge Date (Calculated on) | Comment | | ---------- | ------------- | --------------------------- | ------------------------------ | ---------------------------------------- | | Marcus | $0 | 2026-03-31 | 2026-03-26 | Normal Leaver, receiving no annual bonus | | Jane | $5,000 | 2026-03-31 | 2026-03-26 | Not a leaver, monthly salary | | Jane | $50,000 | 2026-03-31 | 2026-03-26 | Not a leaver, annual bonus | | Jane | $5,000 | 2026-04-30 | 2026-04-25 | Not a leaver, monthly salary | | **Marcus** | **$50,000** | **2026-03-31** | **2026-05-26** | **Backdated bonus adjustment** | Notice how the table naturally documents itself. For Jane, her records maintain a standard 5-day operational offset (Calculated On + 5 days = Payout For), instantly flagging them as standard, in-period calculations. For Marcus's new row, the massive gap between the calculation date (2026-05-26) and the targeted payroll month (2026-03-31) explicitly flags this entry to any auditor as an out-of-cycle retroactive correction. Even without checking the comments, the date misalignment is self-explanatory. If an auditor questions why this adjustment occurred, there is no need to dig through text logs. We simply query Marcus's `HR_Data` records with a `knowledge_date` falling between March 26th and May 26th. The system will instantly surface the May 15th backdated entry changing his status to Good Leaver, providing an airtight, tamper-proof audit trail. --- ## 5. The Conclusion: Simple, Immutable Truth This architecture proves that bitemporal design isn't about adding complexity. It is about removing it. We didn't build a brittle retroactive processing module. We didn't write messy patch scripts. We simply let the data schema do the heavy lifting. Beyond raw simplicity, this setup gives you the ultimate compliance superpower: Total Recall. Because we never overwrote the original March data, you can query your knowledge in March at any point. If an auditor asks you three years from now why Marcus was originally paid $0 in March, you don't have to guess or dig through old PDFs. But auditing the past is only half the power of this engine—in our next Field Note, we will turn the clocks forward to show how this exact same architecture runs forecasts without the need to create a database clone for each forecast.