Skip to content

CMDB History Developer Guide

Ed Mozley edited this page Dec 5, 2026 · 2 revisions

CMDB history - Developer Guide

Each configuration item's change history - after 5.19.0, asked for in #508 by @Dr4inder. User side: CMDB - History. REST: GET /cmdb/objects/{id}/history.

A CI showed what it looked like now, not how it got there. During an incident or an audit the question people ask a CMDB is what changed on this server last week, and who changed it? - and FreeITSM could not answer it. Tickets, changes, problems, tasks, Knowledge and assets all kept a history; the CMDB did not.


1. πŸ“ The files

File Role
includes/cmdb_history.php cmdbHistoryWrite(), cmdbHistoryPropertyRows(), cmdbHistoryFor(), cmdbHistorySource(), cmdbHistoryReady()
includes/services/cmdb.php Writes history in the same transaction as every change: create, update, delete, relationships; historyRelationship() and propertyValuesOf()
includes/services/virtual_estate_cmdb.php Hyper-V discovery's own rename and relationship removal
includes/cmdb/assistant_proposals.php Marks the assistant's writes ($GLOBALS['cmdb_history_source'])
api/cmdb/get_object_history.php The CI page's card
api/v1/resources/cmdb.php, api/v1/lib/routes.php GET /cmdb/objects/{id}/history
cmdb/object.js (historyHtml(), loadHistory()), cmdb/object.php The History card
Table cmdb_object_history (new)

2. πŸ—„οΈ The table

CREATE TABLE IF NOT EXISTS `cmdb_object_history` (
    `id`               BIGINT NOT NULL AUTO_INCREMENT,
    `object_id`        INT NOT NULL,
    `field_kind`       VARCHAR(16) NOT NULL,   -- created | deleted | name | parent | planned | property | relationship
    `field_key`        VARCHAR(100) NULL,      -- property key | relationship type id | class name (deleted)
    `old_value`        TEXT NULL,
    `new_value`        TEXT NULL,
    `value_ref_kind`   VARCHAR(30) NULL,       -- 'cmdb_object' when a property value is a CI id
    `ref_object_id`    INT NULL,               -- relationship: the "to" CI
    `analyst_id`       INT NULL,
    `actor_kind`       VARCHAR(16) NULL,
    `actor_name`       VARCHAR(255) NULL,
    `source`           VARCHAR(16) NOT NULL,   -- app | api | discovery | assistant | workflow | system
    `created_datetime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    ...
    KEY `idx_cmdb_object_history_object` (`object_id`, `created_datetime`),
    KEY `idx_cmdb_object_history_ref` (`ref_object_id`)
);

πŸ”‘ No foreign key to cmdb_objects, on purpose. A delete removes the CI and its whole descendant tree; its history must outlive it, so a DELETE of the CI never touches these rows. analyst_id is history in the analyst lifecycle map.

3. ✍️ Writing it - inside the change's own transaction

Every write path goes through CmdbService (UI, REST, assistant, discovery, demo data), so the history is written there, in the same transaction - a change that rolls back leaves no history row, and a committed one always has its row. updateObject() reads the property values before the write, then writes one row per field that really changed:

// GH #508: one row per field that really changed.
$hist = [];
if ($newName !== $current['name']) $hist[] = ['kind' => 'name', 'old' => $current['name'], 'new' => $newName];
$oldParent = $current['parent_id'] !== null ? (int)$current['parent_id'] : null;
if ($newParent !== $oldParent) $hist[] = ['kind' => 'parent', 'old' => $oldParent, 'new' => $newParent];
...
if ($values) {
    $defs = [];
    foreach (self::classDefs($conn, $classId) as $k => $d) $defs[$k] = $d;
    $hist = array_merge($hist, cmdbHistoryPropertyRows($beforeProps, self::propertyValuesOf($conn, $objectId, $classId), array_keys($values), $defs));
}
cmdbHistoryWrite($conn, $objectId, $ctx, $hist);
$conn->commit();

propertyValuesOf() is TypedFields::readValues() for the one CI, so the before and after are the stored, typed values - a save that sends the same values writes nothing. A reference property stores the referenced id with value_ref_kind; it is named when read, not when written.

Delete writes one row on the CI itself before anything is removed - the class name, the CI's name and how many descendants go with it. The descendants' own histories stay too.

4. πŸ”— Relationships - stored once, read from both ends

public static function historyRelationship(PDO $conn, ?ActorContext $ctx, int $fromId, int $toId, int $typeId, string $action): void
{
    cmdbHistoryWrite($conn, $fromId, $ctx, [['kind' => 'relationship', 'key' => (string)$typeId, 'new' => $action, 'ref_object_id' => $toId]]);
}

cmdbHistoryFor() reads a CI's own rows and relationship rows where it is the ref_object_id, and words each from that end: the "from" CI sees verb (depends on HV02), the "to" CI sees inverse_verb (is depended on by SQL01) - as the Connections card already reads relationships. deleteRelationship() reads the row's ends and type before deleting it, in both its UI and API paths.

5. 🧭 Where a change came from

function cmdbHistorySource(?ActorContext $ctx): string
{
    // A caller acting for something else (the CMDB assistant) says so for its own writes.
    if (!empty($GLOBALS['cmdb_history_source'])) return (string)$GLOBALS['cmdb_history_source'];
    if ($ctx === null) return 'system';
    if ($ctx->source === 'api') return 'api';
    if ($ctx->source === 'workflow') return 'workflow';
    if ($ctx->actorId > 0) return 'app';
    // ActorContext::system('Hyper-V' / 'CMDB assistant' / ...): no person.
    return str_contains(strtolower((string)$ctx->actorName), 'assistant') ? 'assistant' : 'discovery';
}

So a value discovery overwrote can be told apart from one an analyst typed. The assistant creates CIs as the analyst who accepted its plan (fromSession), so cmdbAssistObjectsApply() sets the override for the length of its transaction and clears it in finally.

Hyper-V discovery writes two things itself, not through the service: renaming a bound CI (when sync names is on) and removing relationships it no longer sees. Both now record history with discovery's ActorContext::system('Hyper-V: <connection>').

6. πŸ”’ Reading it - names only within the reader's companies

cmdbHistoryFor($conn, $id, fn(int $other) => analystCanAccessCmdbObject($conn, $me, $other));

TRAP (in the code): the names of other CIs - a parent, the other end of a relationship, a CI-reference property - are read only through the caller's own check. CmdbService keeps neighbours in one company, but the read must not lean on that invariant (old data can straddle companies), exactly as get_object.php does. A CI that exists but may not be seen comes back with no name and *_hidden: true (the card says (not visible to you)); one since deleted has no name and reads (removed). The REST API passes apiKeyCanAccessTenantRow() instead.

7. πŸ–₯️ The card

historyHtml() in cmdb/object.js draws one line per entry - Name: SQL01 β†’ SQL01-PROD, Operating system: 2019 β†’ 2022, Added: depends on HV02 - and under it who, from where and when (fmtWhen(), the reader's own zone). The last 15, then Show all. reloadAndRender() reloads it with the object, so an edit shows in the card straight away.

8. βœ… Tests

FREEITSM_TEST_DATABASE=<throwaway db> php tests/cmdb-history.php - 15 checks through the real CmdbService over a ZZ508 class and three CIs, removed at the end (the service commits its own transactions). Created / rename / property (old, new, label) / an unchanged save writes nothing / the four sources / a relationship stored once and read from both ends with each verb / removing it / a hidden CI not named / a delete row with class and descendant count, and the deleted CI's history still readable / the REST route.

9. 🧭 Design decisions (5 December 2026)

The requester's suggestions, all kept:

Decision Chosen, and why Who
Relationship changes on both CIs Stored once, shown on both, each read with its own verb - no duplicated rows to drift Requester (@Dr4inder)
A reference to a renamed or deleted record Store the id, show the current name or (removed) - the house rule; never a stale name Requester, house rule
A deleted CI's history Kept, plus one row for the delete (who, when, name, class, descendants). No page for it; the REST API reads it Requester
The REST API GET /cmdb/objects/{id}/history, read-only, like GET /tickets/{id}/audit; API changes recorded with source api Requester
Where a change came from app / api / discovery / assistant / workflow Requester. Closest to ITIL (service configuration management): every change to a CI is traceable to who made it and how

10. πŸ—„οΈ Retiring a CI (#510)

(Asked for in #510 by @Dr4inder.) A CI was either planned or in service; one that left service could only stay (in every list and every blast radius, flagged as stale) or be deleted (taking its relationships, its ticket links and its history). Now it can be retired.

One added column, not a new state field. cmdb_objects.retired_datetime DATETIME NULL sits beside is_planned: retired when set, otherwise planned or in service as before. The request suggested replacing is_planned with a three-state field; adding a column gives the same three states without touching the 64 places that read is_planned, the REST contract (is_planned keeps meaning what it meant) or any existing data.

Every reader asks one function (includes/cmdb_retired.php):

function cmdbNotRetiredSql(PDO $conn, string $alias = 'o'): string
{
    return cmdbRetiredReady($conn) ? " AND {$alias}.retired_datetime IS NULL" : '';
}

It is added to the browse list (get_objects.php, unless include_retired), the picker (search_objects.php), the class counts (get_classes.php), data quality's staleness check (cmdbAuditStale()), the REST list - and, the one that matters most, the blast radius. cmdbImpactEdgesFrom() adds it beside the company gate, so it applies to every kind of edge (containment, both relationship directions, dependency properties) on the affected object:

// GH #510: a retired CI has left service - it is not affected, and through it
// nothing further is reached. Added to every query below, beside the company gate.
require_once __DIR__ . '/cmdb_retired.php';
$tenantSql .= cmdbNotRetiredSql($conn, 'o');

A retired CI is never a node, so the walk never continues from it: the app behind a retired server is not reached through it. Its relationships are kept (history and diagrams still make sense) but stop carrying impact while it is retired.

Retiring is CmdbService::retireObject($conn, $ctx, $id, $retire, $withDescendants = true): the CI and, by default, everything beneath it (a child cannot outlive its parent - the rule that makes delete cascade), one retired history row per CI changed, and cmdb.object.updated for workflows. Restoring is the same call with false. The page always includes the descendants; the REST API can pass "retire_descendants": false.

On the page: a Retired chip in the hero, a band with Restore in place of the Retire button, and - when the CI has tickets or a history - the delete dialog leads with Retire keeps all of that; Delete loses it.

Before Database Verification nothing is filtered, and Retire says to run it.

File Change
πŸ”΄ includes/cmdb_retired.php New - cmdbRetiredReady(), cmdbNotRetiredSql()
πŸ”΄ includes/services/cmdb.php retireObject()
πŸ”΄ includes/cmdb_impact.php Retired CIs out of every blast-radius edge
🟑 api/cmdb/retire_object.php New
🟑 api/cmdb/get_objects.php, search_objects.php, get_classes.php, get_object.php, includes/cmdb_audit.php The filter, include_retired, retired_datetime
🟑 api/v1/resources/cmdb.php, openapi_schemas.php retired, retired_at, PATCH {retired}, ?include_retired=1
🟑 cmdb/object.js, object.php, browse.js, index.php Retire / Restore, the chip, the band, Show retired, the pill
🟒 tests/cmdb-retire.php 13 checks

Test. FREEITSM_TEST_DATABASE=<throwaway db> FREEITSM_TEST_URL=http://localhost/<install> php tests/cmdb-retire.php - 13 checks: a UPS failing reaches a server and the app behind it; retiring the server retires its child and keeps both with their relationships and a history row each; the blast radius then stops at the UPS; the list, the picker and the class count leave them out (Show retired brings them back, marked); the REST serialiser says retired; restoring brings them back into the blast radius.

Not built from the request (each could follow): offering to retire a linked CI when its asset is retired; a data-quality check for in-service CIs that depend on a retired one; a Retired pill on a ticket's linked CI.

Decided (5 December 2026):

Decision Options Chosen, and why Who
The state Replace is_planned with a three-state field; add a column Add retired_datetime - the same three states, no change to the 64 readers of is_planned, the REST contract or existing data Me (the request preferred a field; same result, much less risk)
Children Retire alone; with descendants With descendants (the page always; the API may opt out) - a child cannot outlive its parent here Requester
Relationships Removed; kept but inert Kept, carrying no impact while retired Requester
Delete Unchanged; suggest Retire Suggest Retire when there are tickets or history, same permission Requester. Closest to ITIL (service configuration management): retire CIs at the end of their life and keep their records; delete only mistakes

Related pages

CMDB - Developer Guide Β· Impact analysis - Developer Guide Β· REST API - CMDB Β· Developer Tests - Assets

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally