Python architecture of the bookkeeping system
The bookkeeping package separates workflow orchestration, in-memory descriptions of stored data, persistence in the RDF bookkeeping graph, and peripheral retention maintenance. Most harvesting and processing modules should enter through ProcessingInterface or one of the managers in bookkeeping_managers.py; they should not assemble SPARQL or RDF triples themselves. The separate cleaner.py flow removes obsolete graph details and physical data after normal processing has marked entities as deprecated.
The diagram is also available as an editable SVG. Solid arrows show calls, ownership, or data transfer; dashed arrows show Python inheritance. The diagram is a code-structure view, not the RDF data model. See Bookkeeping RDF data model for the graph entities and predicates.
Architecture at a glance
| Layer | Main classes | Responsibility |
|---|---|---|
| Workflow API | ProcessingInterface; DeliveryPackageHandler, UnpackedDeliveryHandler, NASPackageCreator |
Present task-oriented operations to workflow modules and manage longer-lived resources. |
| Unit of work | ProcessingJob and the end indicators |
Hold the state and provenance of one publication while a processing module works on it. |
| Domain and storage model | DataLocation and DataPackage hierarchies |
Describe where bytes are stored, select and hash files, copy content, and represent packages and their components in memory. |
| Persistence gateway | BookkeepingHandler |
Query and update a source's RDF graph, create IRIs and provenance, and translate domain objects into graph records. |
| Peripheral maintenance | Cleaner, PackageCleaner, UnpackedLocationCleaner, NASProcessingFilesCleaner |
Archive and prune deprecated RDF entities, then invoke the configured physical deletion or move strategy. |
| External state | Filesystem, ZIP/SFTP storage, and the RDF triple store | Hold the actual publication data and the authoritative bookkeeping metadata. |
The principal dependency direction is:
workflow module
-> ProcessingInterface -> ProcessingJob -> DataLocation
-> bookkeeping_managers -> DataLocation / DataPackage
|
v
BookkeepingHandler -> RDF graph
scheduled maintenance
-> Cleaner subclasses -> TTLSerializer / BookkeepingHandler
-> filesystem or SFTP deleter
ProcessingInterface and the managers coordinate filesystem operations as well as graph updates. DataLocation objects can inspect or copy bytes, but they do not persist themselves. BookkeepingHandler knows how to persist those objects, but it does not orchestrate a workflow module's temporary directories or package-building loop. The cleaner is a downstream consumer of graph state: it does not participate in job selection and only acts on entities already eligible for retention cleanup.
bookkeepinghandler.py: RDF persistence gateway
BookkeepingHandler is the low-level façade around one bookkeeping graph. Its constructor resolves the graph for a source, obtains the RDFLib graph backed by Virtuoso, binds the project namespaces, identifies the running module and version, and creates PROV agent/activity records for the Prefect flow run. It is a context manager; shutdown_handler() ends the activity, flushes cached triples, and serializes the graph when copy mode is active.
Its responsibilities fall into four groups:
- Store access:
execute_sparql()and the internal retry wrapper centralize graph queries and updates, retrying recognized transient HTTP, connection, and RDFLib failures. - Identity and provenance: methods build publication, location, package, agent, pipeline, and activity IRIs and record creation, derivation, processing, deprecation, deletion, and timestamps.
- Object-to-RDF mapping:
register_location()andregister_package()translateDataLocationandDataPackageinstances into publication, package, component, file, checksum, and provenance triples. - Selection and state transitions: query methods locate publications and locations;
identify_module_job_locations()selects work for a module; update methods change module assignment, flags, file metadata, and processing-folder information.
BookkeepingHandler is intentionally not a generic ORM. The mapping is explicit and type-aware. For example, register_package() creates or reuses a package node, then calls register_location() for each component. Each component is associated with a publication; the Python DataPackage is a container and is not itself the per-publication processing location.
The handler also supports two operational modes:
- In normal mode, reads and writes target the configured source graph.
- In copy mode, reads still use the source graph while writes go to an in-memory target graph that can be serialized as Turtle. This lets processing flows exercise bookkeeping logic without changing the live graph.
A handler is source-scoped. Code that spans multiple sources should let ProcessingInterface open and close the source-specific handlers rather than reusing one handler across unrelated graphs.
processinginterface.py: workflow orchestration and jobs
ProcessingInterface
ProcessingInterface is the standard entry point for processing modules. It turns harvesting configuration into a stream of jobs and hides source switching, graph queries, routing rules, temporary-directory setup, and shutdown handling.
On construction it:
- loads the module's source, group, and pipeline contexts;
- opens a
BookkeepingHandlerfor thegeneralgraph to anchor the overall run activity; - initializes source/pipeline cursors, open-job tracking, copy-mode state, and startup-job recovery state.
obtain_jobs() iterates through the configured sources and pipelines. For each active source it opens a source-specific BookkeepingHandler, calls identify_module_job_locations(), creates a processing activity for every selected location, and converts the result into a ProcessingJob. The interface tracks both open_jobs and active location IRIs to prevent the same location from being handed out twice in one interface instance and to enforce max_parallel.
The normal lifecycle is:
obtain_jobs()
-> ProcessingJob
-> create_temp_folder(job)
-> module changes files
-> return_job(job, temp_dir, processed_dir, changed files...)
Startup modules use the parallel lifecycle obtain_startup_identifier() → create_startup_job() → return_startup_job(). A startup job begins without publication or location nodes in the graph. On return, the interface selects the default or in-LTA pipeline, then the job registers its first NASProcessingFiles location. Batch startup processing can be staged in JSON recovery files through return_startup_job_cached(), process_startup_cache(), and rescue_cached_jobs().
Optional EndOfSourceIndicator and EndOfPipelineIndicator objects are control-flow markers yielded by the generators. They inherit from ProcessingJob for API compatibility, but their finish() method performs no persistence work.
Use ProcessingInterface as a context manager. A source handler must remain open until all jobs from that source have been returned. During exceptional shutdown, the interface attempts to return ordinary open jobs as unsuccessful temporary attempts, then closes both source and general handlers. More detailed calling examples are in Bookkeeping processing interface.
ProcessingJob
ProcessingJob is the stateful unit of work for one publication. It holds:
- publication and processing-location IRIs;
- the article directory and preceding, temporary, and processed folder names;
- previous, current, and next module names plus the pipeline configuration;
- the linked
BookkeepingHandlerand PROV activity; - flags, suspension information, provider identifiers, and the job's open/closed state;
- a
NASProcessingFilesobject inlocationrepresenting the file state.
For an existing publication, the location initially can be a dummy containing only the location identity and path. This avoids fetching every registered file and checksum when the module will only add files. The job enriches the dummy from BookkeepingHandler.get_location_file_info() before modifying or deleting existing entries, or before a complete integrity check.
ProcessingJob.finish() is the commit boundary for a processing step. It interprets the result folder name, merges automatic and manually declared file changes, updates the in-memory NASProcessingFiles, performs requested derivative or full-content checks, persists graph changes through its handler, and finally resolves the temporary folder. A temporary-only result records the attempt and leaves the location assigned for retry. A successful or stopped result updates file provenance, flags, folder information, and module assignment.
Call ProcessingInterface.return_job() rather than invoking finish() directly. The wrapper validates the job, removes it from the interface's open-job and active-location collections, and keeps connection ownership consistent.
datalocation.py: domain objects and storage access
datalocation.py contains two related but deliberately separate class families.
The DataLocation family
DataLocation is the common Python base for data belonging to one independently tracked publication. It stores the RDF location type, provider identifiers, graph IRI or reserved UUID, derivation information, storage selectors, and a cached containedFiles list. File entries use relative paths and SHA-256 hashes; processing locations can add per-file processing status while changes are being assembled.
The base class normalizes provider identifiers, validates relative paths, filters names, caches file analysis, and compares locations by relative path and checksum. Concrete subclasses implement access for their storage form:
DataLocation
├── DataPackageComponent
│ └── PrepackedDataPackageComponent
│ ├── DeliveryDataPackageComponent
│ └── NASDataPackageComponent
│ └── NewNASDataPackageComponent
├── UnpackedDataLocation
│ ├── UnpackedDelivery
│ ├── NASDataPackageComponentInCreation
│ └── NASProcessingFiles
├── AIP
├── DSpaceDataset
└── WDBPlusText
The major branches have distinct meanings:
DataPackageComponentaddresses one publication inside a package ZIP and provides archive-aware enumeration, hashing, extraction, and copy operations. Delivery and NAS component subclasses mainly supply the correct semantic location type and storage role.UnpackedDataLocationaddresses content accessible without first opening a multi-publication package.UnpackedDeliverysupports local and SFTP input.NASProcessingFilesrepresents the module-by-module processing directory and records created, modified, and deleted files.NASDataPackageComponentInCreationis a staging object used while writing one new ZIP component; after it is added to a package it is represented by aNewNASDataPackageComponent.AIP,DSpaceDataset, andWDBPlusTextrepresent downstream archival, repository, and converted-text locations with type-specific identifiers.
These base classes are “abstract” by convention rather than through Python's abc module. Application code should instantiate the concrete subclass that matches the physical and semantic storage type.
The DataPackage family
DataPackage is not a subclass of DataLocation. It models a multi-publication archive as package metadata plus a componentList of DataPackageComponent objects. It owns archive open/close behavior, component construction, and JSON serialization used for recovery.
DataPackage
├── DeliveryDataPackage
└── NASDataPackage
└── NewNASDataPackage
DeliveryDataPackage describes a supplier package, possibly through a local working copy. NASDataPackage describes a retained package on backed-up NAS storage. NewNASDataPackage owns the temporary-to-final ZIP lifecycle while a new NAS package is assembled. The separation between a package and its components matters at persistence time: the package is registered once, while every component is registered as a publication location linked to that package.
For more detail about selectors, package/component registration, and repacking examples, see DataPackages and DataLocations.
bookkeeping_managers.py: additional high-level interfaces
bookkeeping_managers.py provides workflow-oriented adapters for delivery registration and package creation. They compose the domain objects with a BookkeepingHandler and are peers of ProcessingInterface, not subclasses of it.
| Manager | Main domain objects | Purpose |
|---|---|---|
DeliveryPackageHandler |
DeliveryDataPackage, optionally NASDataPackage |
Describe components in an existing delivery package, hash them, and register the package; optionally register a permanent NAS copy. |
UnpackedDeliveryHandler |
UnpackedDelivery |
Select, analyse, and register a delivery that is directly accessible locally or through SFTP. |
NASPackageCreator |
NASDataPackageComponentInCreation, NewNASDataPackage |
Copy or write per-publication components into size/count-bounded NAS ZIPs and register completed packages. |
The package managers use JSON recovery records before graph registration. BookkeepingHandler.register_package(..., append_mode=True) can then finish a package whose node or early components were persisted before a transient failure. DeliveryPackageHandler can create a handler from a source, and NASPackageCreator can create one from a provider; UnpackedDeliveryHandler requires an injected handler. Injecting one shared, context-managed handler is preferable when several managers participate in one provenance session.
cleaner.py: peripheral retention maintenance
cleaner.py is deliberately outside the normal ProcessingInterface job lifecycle. Its cleaner() Prefect flow iterates over the configured sources, opens a source-specific BookkeepingHandler and SFTP connector, attaches a TTLSerializer to that handler, and runs cleanup strategies for four RDF entity types in this order:
wdmvoc:NASDataPackage;wdmvoc:DeliveryDataPackage;wdmvoc:UnpackedDelivery;wdmvoc:NASProcessingFiles.
The class hierarchy uses a small strategy-based design:
Cleaner
├── PackageCleaner
└── UnpackedLocationCleaner
└── NASProcessingFilesCleaner
The base Cleaner receives the handler, serializer, RDF entity type, optional SFTP connector, and local/SFTP deletion functions. A subclass supplies an identification_method and serialization_method. iterate_deprecated_entities() requests eligible entities in batches of 20 until the final short batch.
PackageCleaner first asks BookkeepingHandler.mark_packages_deprecated() to derive package deprecation from component state, then selects removable packages with find_deprecated_packages(). UnpackedLocationCleaner selects already deprecated unpacked locations; for UnpackedDelivery, it first calls mark_lta_ingested_deliveries_deprecated(). NASProcessingFilesCleaner reuses that logic but supplies the processing-folder operation instead of a file deleter.
For each selected entity, remove_and_serialize_single_entity() performs two phases in a fixed order:
TTLSerializerwrites the entity's package or location subgraph into a Turtle archive, removes mutable details from the live graph, and records the entity as deleted.- The configured deleter removes the local/mounted file or SFTP object; processing folders use their dedicated move/delete function.
These phases are not one transaction. If the physical operation fails after serialization and graph pruning, the graph already contains the deletion timestamp and normal cleanup selection will not automatically retry the entity. Operational recovery must therefore check both the Turtle archive and the storage path.
The use_fake_deleters option defaults to True. This substitutes logging/validation functions for ordinary mounted-file and SFTP removal, but the NASProcessingFiles strategy still calls nas_folder_mover(), which relocates the folder. A default cleaner run must therefore still be treated as filesystem-changing maintenance. See Bookkeeping Cleaner for eligibility rules, archive locations, and operational caveats.
End-to-end data flows
Process an existing publication
ProcessingInterfacereads the module's configured pipelines and opens the source handler.BookkeepingHandler.identify_module_job_locations()selects an eligibleNASProcessingFileslocation.- The interface creates an activity and a
ProcessingJob, then the workflow copies the previous state to a temporary folder. - The workflow reports created, modified, and deleted relative paths when returning the job.
ProcessingJob.finish()updates itsNASProcessingFiles, validates the result, and asksBookkeepingHandlerto persist file and routing changes.- The temporary folder is resolved to its final module or stop-processing name, and the interface releases the job.
Register or repack a delivery
- A delivery manager constructs
UnpackedDeliveryorDeliveryDataPackageComponentobjects and analyses their files. NASPackageCreator, when used, copies each delivery into aNASDataPackageComponentInCreationand verifies checksum identity.- The staging component is inserted into a
NewNASDataPackage, becoming a packaged component description. - The finished package is serialized for recovery and then passed to
BookkeepingHandler.register_package(). - The handler creates the package node and registers every component location against its publication with derivation provenance.
Clean deprecated storage
- Normal workflow operations mark superseded locations or package components as deprecated in the graph.
- The
cleaner()flow opens one bookkeeping session per source and constructs the cleaner subclass for each supported entity type. - The subclass derives or selects eligible deprecated entities through
BookkeepingHandler. TTLSerializerarchives the relevant RDF subgraph and prunes mutable graph details.- The configured local, SFTP, or processing-folder strategy removes or relocates the physical data.
Boundaries and maintenance rules
- Keep workflow-specific ordering and configuration decisions in
ProcessingInterfaceor a manager, not inDataLocationsubclasses. - Keep RDF vocabulary, IRI construction, SPARQL, and graph mutation in
BookkeepingHandler. - Add storage-format behavior—enumeration, hashing, extraction, and copying—to the appropriate
DataLocationorDataPackagesubclass. - Treat graph metadata and bytes as two coordinated external states rather than one transaction. Preserve the existing recovery-file and rescue-folder paths when changing write order or error handling.
- Keep retention decisions graph-driven. The cleaner must select entities through
BookkeepingHandlerand archive their RDF subgraphs before physical removal; changes to this ordering require an explicit recovery design. - Track handler ownership explicitly.
ProcessingInterfacecloses the general and source handlers it opens, andNASPackageCreatorcloses a handler it created itself.DeliveryPackageHandler.__exit__()currently reports an open package but does not close a self-created handler; callers should therefore prefer an injected context-managed handler or close the created handler explicitly.UnpackedDeliveryHandleralways uses an injected handler and does not close it. - Preserve the distinction between a package and a per-publication location. Python inheritance and RDF subclass relationships are not identical; consult the RDF data model before changing either hierarchy.
Source map
bookkeeping/bookkeepinghandler.py: graph access, registration, selection, state transitions, and provenance.bookkeeping/processinginterface.py: module-facing job orchestration andProcessingJobfinalization.bookkeeping/datalocation.py: data-location/package hierarchy and physical content operations.bookkeeping/bookkeeping_managers.py: additional delivery and packaging interfaces.bookkeeping/cleaner.py: peripheral Prefect cleanup flow and entity-specific cleanup strategies.bookkeeping/serializer.py: Turtle subgraph archives and graph-pruning bridge used by the cleaner.bookkeeping/wdmvoc.pyandbookkeeping/definitions.py: RDF terms, namespaces, processing states, and shared definitions.bookkeeping/store_functions.py: configured RDF graph construction.