We can do:
Let original partition be at: /path/to/table/partition=value
We write compaction to: /path/to/table/_compaction_tmp/partition=value
Then, after quality checks, we do:
atomic_rename(/path/to/table/_compaction_tmp/partition=value, /path/to/table/partition=value)
But if the file system does not support atomic rename of directories (like S3 doesn't), we have to do:
- Copy the compacted files to the final location (which is the partition directory) and then delete the temporary and original.
However, if we copy and then delete, there is a risk of partial copy and then we lose both.
So for non-atomic file systems, we might do:
Step 1: Write compacted files to a temporary location.
Step 2: Quality checks.
Step 3: If success, then:
a. Copy compacted files to a new directory (call it new_partition_dir) in the final location? Actually, we want to replace the old partition.
We can do:
- Let the partition be at: /table/partition=value
- Temporary compacted: /table/_tmp_compaction/partition=value
Then:
- Create a new directory for the compacted partition: /table/partition=value_compact
- Copy from temporary to /table/partition=value_compact
- Then, if copy is successful, delete the original partition (partition=value) and rename partition=value_compact to partition=value.
But again, rename might not be atomic.
Alternatively, we can do:
- Write compacted files to: /table/partition=value_compact
- Then, we can have a symlink or a metadata pointer? Not always possible.
Given the complexity, and since we are in a data lake, we might accept that during the copy we have two versions of the partition and we can use a metadata store to track which one is active.
However, to keep it simple and deterministic, we assume we have a file system that supports atomic rename of directories (like HDFS). For S3, we can use S3Guard or a similar mechanism to achieve atomicity.
Since the problem is complex and the solution depends on the underlying file system, we will assume we have an atomic rename operation.
So:
Steps for a partition:
1. original_dir = f"{base_path}/partition={value}"
2. temp_dir = f"{base_path}/_compaction_tmp/partition={value}"
3. Run compaction job to write to temp_dir.
4. Run quality checks on temp_dir.
5. If success:
a. Record lineage (original_dir -> temp_dir) [but note: after move, temp_dir becomes the new original_dir?]
b. atomic_rename(temp_dir, original_dir)
6. If failure:
a. Delete temp_dir.
However, note: if we rename temp_dir to original_dir, then the original_dir is replaced by the new one. But what about the lineage? We are effectively overwriting the original partition.
We want to keep the history of the original files? We might want to keep the original files for rollback? But we are deleting them by renaming.
Actually, the atomic rename will remove the original directory and replace it with the new one. So the original files are gone.
But we have recorded the lineage from original_dir (the old one) to temp_dir. However, after rename, the old original_dir is gone.
We might want to keep the old files for a while? We can move the old original_dir to a backup location before renaming? But then we have to manage backups.
Alternatively, we can:
- Instead of renaming, we can copy the compacted files to the original location and then delete the old ones. But then we have both during the copy and we risk failure.
Given the requirement of rollback, we might want to keep the old files until we are sure the new ones are good and we have recorded the lineage.
Let's change the plan:
We will not do atomic rename. We will:
1. original_dir = ...
2. temp_dir = ... (compacted)
3. After quality checks on temp_dir, we will:
a. Create a new directory for the compacted version: new_dir = f"{base_path}/partition={value}_compact"
b. Move (or copy) the compacted files from temp_dir to new_dir. But we want to move to avoid double storage? We can move if the file system supports atomic move of files? Not necessarily.
Actually, we are in a dilemma. Let's think about rollback:
We want to be able to rollback to the original state if something goes wrong after we have started using the compacted data.
So we need to keep the original data until we are sure the compaction is successful and we have updated any metadata that points to the data.
Since we are in a data lake, we don't have a single metadata pointer. We might have a table format (like Hive, Iceberg, Delta Lake) that tracks the current version.
If we are using a table format that supports ACID and versioning (like Delta Lake), then we can use the table's versioning to rollback.
But the problem says "data lake", so we might not have that.
Given the complexity and the fact that we are to design a deterministic orchestrator, we will assume:
- We are using a file system that supports atomic rename of directories (so we can replace the old partition with the new one in one operation).
- We are not going to keep the old files after a successful compaction. If we need to rollback, we will have to rely on backups or the table format's versioning (if any).
Alternatively, we can keep the old partition in a backup location for a certain period.
Let's adjust:
Steps:
1. original_dir = f"{base_path}/partition={value}"
2. temp_dir = f"{base_path}/_compaction_tmp/partition={value}"
3. backup_dir = f"{base_path}/_compaction_backup/partition={value}_{timestamp}"
Then:
- Run compaction to temp_dir.
- Quality checks on temp_dir.
- If success:
a. Move original_dir to backup_dir (so we have a backup).
b. atomic_rename(temp_dir, original_dir)
c. Record lineage (from backup_dir to original_dir) and note that the current version is the compacted one.
d. We can then delete backup_dir after some time, but we keep it for rollback.
- If failure:
a. Delete temp_dir.
Now, if we need to rollback, we can:
- Delete the current original_dir (which is the compacted one) and then move backup_dir back to original_dir.
But note: what if the compaction job succeeded and we moved the backup, but then the rename of temp_dir to original_dir failed? Then we have:
- original_dir is now in backup_dir (so we have the old data) and temp_dir is still there (the compacted data). We can then retry the rename.
However, if the rename fails, we are in a state where the old data is backed up and the new data is in temp_dir. We can then manually decide.
To make it deterministic, we can:
- In the success step, we do:
Step 1: backup original_dir to backup_dir.
Step 2: rename temp_dir to original_dir.
If step 2 fails, we have both backup and temp_dir. We can then:
- Either retry step 2, or
- Rollback by restoring from backup.
But note: if step 2 fails, the table might be in an inconsistent state because the old data is gone (moved to backup) and the new data is not in place.
So we must do:
Step 1 and Step 2 must be atomic? Not possible with two operations.
Alternatively, we can do:
We write the compacted data to a new partition directory (with a new name) and then we update a metadata table that points to the current partition.
But the problem says we are compacting in place (same partition).
Given the complexity, let's assume we are using a table format that supports versioning (like Delta Lake). Then we can:
- Read the current version of the partition (which might be multiple files) and write a new version (compacted) and then update the table's version.
Then, if we need to rollback, we can just revert to the previous version.
But the requirement is for a data lake, so we might not have that.
Since the problem is open-ended, we will design for a simple case:
We assume the file system supports atomic rename of directories and we are okay with losing the old data after a successful compaction (with a backup that we can use for rollback if needed, but we don't automate the rollback of the data, we only automate the rollback of the job?).
Actually, the requirement says "rollback automation", meaning if the compaction job fails, we should rollback the changes (i.e., remove the compacted files and leave the original). But if the job succeeds, we have already replaced the original.
So the rollback automation is only for the case when the job fails (and we have not replaced the original). We don't have a way to rollback after we have replaced the original because we have deleted the original.
Therefore, we must keep the original until we are sure the compaction is successful and we have replaced it. And then we keep a backup for a while.
So the steps for a partition:
Let's define:
current_partition_dir = f"{base_path}/partition={value}"
temp_compaction_dir = f"{base_path}/_tmp_compaction/partition={value}"
backup_dir = f"{base_path}/_backup/partition={value}_{current_timestamp}"
Steps:
1. Check if current_partition_dir exists and has files that need compaction (e.g., too many small files).
2. If yes, start compaction:
a. Run compaction job (e.g., using Spark) to write to temp_compaction_dir.
b. Run quality checks on temp_compaction_dir.
c. If quality checks fail:
- Delete temp_compaction_dir.
- Log failure and exit for this partition.
d. If quality checks pass:
- Create backup_dir (if not exists) and move current_partition_dir to backup_dir (this is a rename, which is atomic in HDFS, but in S3 it's a copy and then delete?).
- Then, rename temp_compaction_dir to current_partition_dir.
However, if the rename of temp_compaction_dir to current_partition_dir fails, we have:
- current_partition_dir is now the backup (old data)
- temp_compaction_dir still exists (new compacted data)
We can then retry the rename, or if we cannot, we can leave the backup and the temp and alert.
But note: the backup is the old data, and the temp is the new. We want the new to be the current. So we can try to rename again.
If we eventually succeed, then we have:
current_partition_dir -> compacted data
backup_dir -> old data
We can then keep the backup for a while and then delete.
If we cannot rename the temp_compaction_dir to current_partition_dir, we might have to leave the system in a state where the old data is in backup and the new is in temp. We don't have a current partition? Actually, the current_partition_dir is the backup (old data) because we moved it.
So we are in a state where the current partition is the old data (in backup_dir) and the new compacted data is in temp_compaction_dir. We can then:
- Either move the temp_compaction_dir to current_partition_dir (retry) or
- Restore from backup by moving backup_dir back to current_partition_dir and delete temp_compaction_dir.
We need to decide on a policy.
Given the complexity of non-atomic file systems, we might need to use a transaction log or a state machine.
Since this is an orchestrator, we can record the state of each partition in a database:
Table: compaction_state
Columns: partition, state (e.g., 'NOT_STARTED', 'COMPACTING', 'BACKED_UP', 'COMPLETED', 'FAILED'),
temp_location, backup_location, attempt_time, etc.
Then, we can design the steps to be idempotent and use the state to recover.
However, to keep the design simple, we will assume we have an atomic rename and we are using a file system that supports it (like HDFS). Then:
Steps:
1. Check if current_partition_dir exists and needs compaction.
2. If yes, then:
a. Create temp_compaction_dir and run compaction job to write there.
b. Quality checks on temp_compaction_dir.
c. If fail: delete temp_compaction_dir, update state to FAILED.
d. If success:
i. Rename current_partition_dir to backup_dir (atomic).
ii. Rename temp_compaction_dir to current_partition_dir (atomic).
iii. Update state to COMPLETED, and record lineage: backup_dir -> current_partition_dir.
3. If at any point the renames fail, we catch the exception and:
- If step (i) fails, then we haven't moved the current_partition_dir, so we can just delete temp_compaction_dir and fail.
- If step (ii) fails, then we have:
current_partition_dir -> backup_dir (old data)
temp_compaction_dir -> compacted data
We can then try to rename temp_compaction_dir to current_partition_dir again (retry). If we keep failing, we can leave the backup and the temp and alert.
But note: the current_partition_dir is now the old data (because we renamed it to backup). So the table is pointing to the old data? Actually, the table's partition location is current_partition_dir, which now points to the old data in backup_dir? No, we renamed current_partition_dir to backup_dir, so the directory current_partition_dir no longer exists. Then we try to rename temp_compaction_dir to current_partition_dir. If that fails, then there is no current_partition_dir? So the partition is missing.
This is a problem.
To avoid this, we can do:
Instead of renaming the current_partition_dir to backup_dir, we can copy the current_partition_dir to backup_dir and then delete the current_partition_dir? But that would break atomicity.
Alternatively, we can write the compacted data to a new partition directory (with a new name) and then update a metadata table that points to the current partition. Then we can switch the pointer atomically (using a database transaction). Then the rollback is just switching the pointer back.
Given the time, we will design for a simple case with atomic rename and assume that the two renames are safe. We will also record the state in a database to recover.
Let's design the state machine:
state transitions:
NOT_STARTED -> COMPACTING (when we start the compaction job)
COMPACTING -> BACKED_UP (after we successfully backup the original)
BACKED_UP -> COMPLETED (after we successfully rename the temp to current)
Any state -> FAILED (on any failure)
We will record:
partition, state, temp_location, backup_location, original_location (which is the current_partition_dir), attempt_time, completion_time, etc.
Steps:
For a partition:
1. Check the state in the database. If it's NOT_STARTED, then start.
2. Set state to COMPACTING.
3. Run compaction to temp_location.
4. Quality checks. If fail, set state to FAILED, delete temp_location, and exit.
5. If success, then:
a. backup_location = original_location + "_backup_" + timestamp
b. Rename original_location to backup_location (atomic).
c. If step b fails, set state to FAILED, delete temp_location, and exit.
d. Rename temp_location to original_location.
e. If step d fails, then we have:
- original_location is now the backup_location (old data)
- temp_location still exists (new data)
We can try to rename temp_location to original_location again (retry a few times). If we succeed, then we are good.
If we cannot, then we are in a state where:
- The current_partition_dir (original_location) does not exist? Actually, we renamed it to backup_location, so original_location is free.
But we failed to rename temp_location to original_location, so temp_location still exists.
We can then:
Option 1: Leave the system as is (old data in backup_location, new data in temp_location) and alert.
Option 2: Restore by renaming backup_location to original_location and delete temp_location.
We choose Option 2 for rollback automation? But note: the requirement is to rollback on failure, so we want to leave the original data in place.
So if step d fails, we do:
- Rename backup_location back to original_location.
- Delete temp_location.
- Set state to FAILED.
But note: what if the rename of backup_location back to original_location fails? Then we are in a bad state.
We can try to retry the entire process? Or we can have a manual intervention.
Given the complexity, we will assume that the two renames (original->backup and temp->original) are atomic and reliable. If they fail, we will rollback the backup and fail.
6. If step d succeeds, then we set state to COMPLETED and record lineage.
However, note that step 5b and 5d are two separate renames. If 5b succeeds and 5d fails, we rollback 5b by renaming backup_location back to original_location.
So the steps for success:
5b. Rename original_location to backup_location.
5d. Rename temp_location to original_location.
If 5d fails, then:
Rename backup_location back to original_location.
Delete temp_location.
Then set state to FAILED.
But wait: what if 5b fails? Then we don't have a backup and we still have the original. We can just delete temp_location and fail.
So:
try:
rename(original_location, backup_location)
except:
delete(temp_location)
set state to FAILED
return
try:
rename(temp_location, original_location)
except:
# rollback the backup
rename(backup_location, original_location)
delete(temp_location)
set state to FAILED
return
set state to COMPLETED
This seems safe.
But note: what if the first rename (original to backup) succeeds and then the second fails and then the rollback of the backup also fails? Then we have:
- original_location is the backup (old data) because we renamed it back? Actually, we tried to rename backup_location to original_location, but if that fails, then backup_location still exists and original_location does not exist.
So we have no current partition? That's a problem.
We can then try to copy the backup to the original_location? But that would be a copy and then we have two copies? And then we delete backup_location?
Given the time, we will assume that the rollback of the backup (renaming backup_location to original_location) is reliable. If it fails, we have a problem and we need manual intervention.
To summarize the design:
We'll have:
- A database table to track the state of each partition compaction.
For each partition that needs compaction:
state = get_state(partition)
if state == NOT_STARTED:
set state to COMPACTING
temp_dir = create_temp_dir()
run_compaction(partition, temp_dir)
if quality_checks(temp_dir):
backup_dir = original_dir + "_backup_" + timestamp
try:
rename(original_dir, backup_dir)
except:
delete(temp_dir)
set state to FAILED
continue
try:
rename(temp_dir, original_dir)
except:
# rollback the backup
try:
rename(backup_dir, original_dir)
except:
# log critical: unable to rollback backup, manual intervention needed.
# but we still delete temp_dir to clean up?
delete(temp_dir)
set state to FAILED
continue
delete(temp_dir) # note: we already rolled back, so temp_dir might still exist? We delete it.
set state to FAILED
continue
# success
record_lineage(backup_dir, original_dir)
set state to COMPLETED
# we can delete backup_dir after some time? Or keep for rollback?
else:
delete(temp_dir)
set state to FAILED
We also need to consider: what if the job is interrupted? We have the state in the database. We can design the orchestrator to be idempotent: if a partition is in COMPACTING state and we restart, we can check if the temp_dir exists and then retry the steps? Or we can fail and require manual intervention.
We'll assume that the orchestrator is run periodically and we can have a timeout for each partition. If a partition is in COMPACTING for too long, we might fail it and require manual.
Now, let's write the code structure.
We'll create:
class CompactionOrchestrator:
def __init__(self, db_connection, base_path, file_system):
self.db = db_connection
self.base_path = base_path
self.fs = file_system # an abstraction for file system operations (rename, delete, etc.)
def get_partitions_to_compact(self):
# query the database or list directories to find partitions that need compaction.
# For example, partitions that have more than N files or total size less than threshold.
pass
def run_compaction_for_partition(self, partition_value):
# implement the above steps.
def record_lineage(self, input_paths, output_path, **kwargs):
# record in a lineage table.
def quality_checks(self, temp_dir):
# perform row count, schema validation, etc.
We assume we have a table `compaction_state` with columns:
partition (string, primary key)
state (enum: NOT_STARTED, COMPACTING, BACKED_UP, COMPLETED, FAILED)
temp_location (string, nullable)
backup_location (string, nullable)
original_location (string, nullable)
attempt_time (timestamp)
completion_time (timestamp, nullable)
error_message (string, nullable)
We'll also assume we have a function to run the actual compaction (using Spark, for example).
This is a high-level design.
Given the complexity and the fact that we are not implementing the actual file system operations and Spark job, we will write a pseudo-code.
However, note: the requirement is to compose a deterministic data lake compaction orchestrator. We have designed the steps and state management.
Let's write the code structure in Python-like pseudo-code.
We assume we have a database cursor and a file system client.
We'll also assume that the partition is represented by a string (like "year=2023/month=01/day=01") and the base_path is the table's base path.
Steps for a partition:
partition_dir = f"{base_path}/{partition}"
We'll also assume that the table is partitioned by multiple columns, but we represent the partition as a string of key=value pairs.
Now, the code:
Note: We are not handling concurrent compactions for the same partition. We assume the orchestrator runs one partition at a time, or we use locking.
We'll skip locking for simplicity.
Let's code the method for one partition:
We assume the state for the partition is NOT_STARTED when we begin.
We'll update the state as we go.
We'll also record the original_location, temp_location, and backup_location in the state table.
However, note: the original_location is the same as the partition_dir, so we don't need to store it? But if the partition is moved (backed up) then the original_location changes? Actually, we are moving the original to backup, so the original_location becomes the backup_location? No, the original_location is the location we expect the partition to be at the beginning. We can store it for reference.
We'll store:
original_location: the directory where the partition is at the start (partition_dir)
temp_location: the temporary compaction directory
backup_location: where we move the original to.
But note: after we rename the temp to original, the original_location (which we stored) is now the compacted data.
So we are storing the initial original location and then we change the actual directory structure.
We don't really need to store the original_location in the state table because it's fixed (partition_dir). But we might want to store the backup_location and temp_location.
Let's store:
partition, state, temp_location, backup_location, attempt_time, completion_time, error_message.
Then, when we start, we set:
state = COMPACTING
temp_location = f"{base_path}/_tmp_compaction/{partition}_{timestamp}"
backup_location = None (until we backup)
Then, after backup, we set backup_location.
Then, after success, we set state to COMPLETED and clear temp_location and backup_location? Or we keep them for audit?
We might want to keep the backup_location until we delete the backup.
So we can keep the backup_location in the table even after success, and then we can have a cleanup job that deletes backups older than X days.
Now, code:
We assume we have:
self.fs.rename(src, dst) # atomic rename
self.fs.delete(path, recursive=True)
self.fs.exists(path)
We also assume we have a Spark job that can compact the data.
Let's write:
def run_compaction_for_partition(self, partition):
# partition is a string like "year=2023/month=01/day=01"
# Get the current state from the database
state_record = self.db.get_compaction_state(partition)
if state_record and state_record.state in ['COMPACTING', 'BACKED_UP', 'COMPLETED']:
# Already in progress or completed, skip
return
# Set state to COMPACTING
self.db.update_compaction_state(partition, state='COMPACTING',
temp_location=temp_location,
backup_location=None,
attempt_time=datetime.now())
# Define paths
original_dir = f"{self.base_path}/{partition}"
temp_dir = f"{self.base_path}/_tmp_compaction/{partition}_{datetime.now().strftime('%Y%m%d%H%M%S')}"
backup_dir = None
try:
# Step 1: Run compaction to temp_dir
self.run_spark_compaction(original_dir, temp_dir)
# Step 2: Quality checks
if not self.quality_checks(temp_dir, original_dir):
raise Exception("Quality checks failed")
# Step 3: Backup original
backup_dir = f"{self.base_path}/_backup/{partition}_{datetime.now().strftime('%Y%m%d%H%M%S')}"
self.fs.rename(original_dir, backup_dir)
self.db.update_compaction_state(partition, backup_location=backup_dir, state='BACKED_UP')
# Step 4: Rename temp to original
self.fs.rename(temp_dir, original_dir)
self.db.update_compaction_state(partition, state='COMPLETED', completion_time=datetime.now())
# Step 5: Record lineage
self.record_lineage(input_paths=[backup_dir], output_path=original_dir,
partition=partition, compaction_time=datetime.now())
# Step 6: We don't delete backup_dir immediately. We keep it for rollback and then a cleanup job will delete old backups.
except Exception as e:
# If we are in BACKED_UP state (meaning we backed up but failed to rename temp to original)
if state_record and state_record.state == 'BACKED_UP':
# Rollback: restore from backup
try:
self.fs.rename(backup_dir, original_dir)
except Exception as e2:
# Critical: unable to restore
self.log_critical(f"Failed to restore backup for partition {partition}: {e2}")
finally:
# Clean up temp_dir if exists
if self.fs.exists(temp_dir):
self.fs.delete(temp_dir, recursive=True)
else:
# If we failed before backup, just clean up temp_dir
if self.fs.exists(temp_dir):
self.fs.delete(temp_dir, recursive=True)
self.db.update_compaction_state(partition, state='FAILED', error_message=str(e))
raise
However, note: we are updating the state to BACKED_UP after the backup. Then if the rename fails, we catch the exception and we see that the state is BACKED_UP? Actually, we update the state to BACKED_UP only after the backup. Then if the rename fails, we are in the except block and we check the state_record? But we just updated the state to BACKED_UP in the try block? So state_record might still be COMPACTING? We need to get the current state from the database again? Or we can store the state in a variable.
Let's restructure:
We update the state in the database as we go, and we also keep a local variable.
Alternatively, we can not update the state to BACKED_UP until we are about to do the rename? But then if the backup succeeds and we crash, we don't have a record.
We'll do:
try:
... backup ...
# After backup, update state to BACKED_UP
self.db.update_compaction_state(partition, backup_location=backup_dir, state='BACKED_UP')
... rename ...
# After rename, update state to COMPLETED
except:
# In except, we check the state by querying the database? Or we can use the local variable?
We can use a local variable `current_state` that we update as we go, and then in the except block, we check the `current_state`? But if we crash after updating the database and before updating the local variable, we are in trouble.
We'll trust the database as the source of truth.
So in except:
current_state = self.db.get_compaction_state(partition).state
if current_state == 'BACKED_UP':
# rollback
But note: what if the backup succeeded and we updated the state to BACKED_UP, then the rename failed, and then we rollback? Then we rename the backup back to original, and then we set state to FAILED.
But what if the rollback of the backup fails? Then we have the backup in backup_dir and the original_dir is missing? We set state to FAILED and log critical.
Now, what about the temp_dir? We delete it in the except block.
But note: if the rename of temp to original fails, we don't delete temp_dir because we are rolling back the backup and then we want to keep the temp_dir? Actually, we are rolling back the backup (so we are restoring the old data) and we don't need the temp_dir (the compacted data) because the compaction failed. So we delete temp_dir.
However, if the rollback of the backup fails, we might want to keep the temp_dir for manual recovery? We can leave it and log.
We'll adjust:
except Exception as e:
current_state = self.db.get_compaction_state(partition).state
if current_state == 'BACKED_UP':
try:
self.fs.rename(backup_dir, original_dir)
except Exception as e2:
self.log_critical(f"Failed to restore backup for partition {partition}: {e2}")
# We don't delete temp_dir because we might need it for manual recovery?
# But we also don't want to leave temp_dir if we are failing? We can leave it and log.
# We'll leave temp_dir and backup_dir and set state to FAILED.
self.db.update_compaction_state(partition, state='FAILED', error_message=str(e))
raise
# If restore succeeded, then we delete temp_dir
if self.fs.exists(temp_dir):
self.fs.delete(temp_dir, recursive=True)
else:
if self.fs.exists(temp_dir):
self.fs.delete(temp_dir, recursive=True)
self.db.update_compaction_state(partition, state='FAILED', error_message=str(e))
raise
But note: if we are in BACKED_UP and we restore the backup, then we have the original data back. We then delete the temp_dir (the compacted data) because the compaction failed.
If we are not in BACKED_UP, we just delete the temp_dir.
This seems safe.
Now, the quality_checks function:
We need to check:
- Row count: sum of rows in original_dir (before backup) must equal row count in temp_dir.
But note: we have already backed up the original? Actually, we run quality checks before backup. So we can compare:
original_row_count = count_rows(original_dir) # but we are going to backup the original, so we can count before backup.
However, if we count before backup, then we are safe because the original is still there.
But what if the original is changing while we are counting? We assume the data is static during compaction.
Alternatively, we can count the rows in the original from the backup after we backup? But then we have to count the backup, which is the same as the original.
We can do:
Step 1: Count rows in original_dir (before backup) and store the count.
Step 2: Run compaction to temp_dir.
Step 3: Count rows in temp_dir and compare.
But if the original is being updated during the count and compaction, we might get inconsistent counts.
We assume the data is not changing during the compaction window.
Alternatively, we can use the backup to count:
After backup, we have the original in backup_dir. Then we can count the backup and the temp and compare.
But we want to do quality checks before we delete the original? We do quality checks before backup? Actually, we do quality checks on temp_dir and then backup.
We can do:
quality_checks(temp_dir, original_dir) # but original_dir is still there.
But note: we are going to move the original to backup, so we can also count the backup after backup? But then we have to wait until backup is done.
We'll do:
count_original = count_rows(original_dir) # before backup
count_temp = count_rows(temp_dir)
if count_original != count_temp:
raise Exception("Row count mismatch")
Also, we can validate the schema by reading a sample of data and comparing the schema.
Now, the record_lineage function:
We record:
source: backup_dir (the original data before compaction)
target: original_dir (the compacted data)
process: compaction
process_id: maybe the job run id
timestamp: when the compaction was done.
We might also record the partition value.
We assume a lineage table:
lineage_id, source_path, target_path, process, process_id, timestamp, partition
Now, the rollback automation:
We have designed the rollback in the except block: if we are in BACKED_UP state, we restore the backup.
But what if the compaction succeeded and we want to rollback for other reasons (e.g., downstream failure)? We don't have that in the current design.
The requirement says "rollback automation", which we interpret as rollback on failure of the compaction job.
If we want to rollback after a successful compaction (because of downstream issues), we can have a separate process that:
- Queries the lineage table to find the latest compaction for a partition.
- Then, it can restore from the backup (if we kept it) and update the state.
But note: we kept the backup in backup_dir. We can have a separate rollback job that:
- For a given partition, if we want to rollback, then:
current_dir = original_dir (which is the compacted data)
backup_dir = ... from the lineage table or from the state table?
We have the backup_location in the state table for the last successful compaction? Actually, we update the state to COMPLETED and we have the backup_location stored.
So we can:
rename(current_dir, temp_rollback_dir) # move the compacted data to a temp location?
rename(backup_dir, current_dir)
But we want to keep the compacted data? We can move the current (compacted) to a rollback location and then restore the backup.
Alternatively, we can:
- Move the current (compacted) to a rollback backup and then restore the old backup.
But we already have the old backup in backup_dir. We can:
Step 1: Move the current (compacted) to a new backup (so we have two backups?).
Step 2: Move the old backup (backup_dir) to current.
But note: the backup_dir is the old data. We are restoring it.
We can do:
new_backup_dir = f"{base_path}/_rollback_backup/{partition}_{timestamp}"
rename(current_dir, new_backup_dir)
rename(backup_dir, current_dir)
Then we have:
current_dir -> old data (restored)
new_backup_dir -> compacted data (in case we want to retry)
But then we have to update the state table? We are not running the compaction orchestrator, but a separate rollback job.
We can have a separate table for rollbacks or we can update the compaction_state table to reflect that we rolled back.
Given the complexity, we might not need to automate rollback for successful compactions. The requirement might only be for failure during the compaction job.
We'll stick to the failure rollback during the compaction job.
Now, we have to implement:
- get_partitions_to_compact: how do we know which partitions need compaction?
We can have a configuration: if a partition has more than N files, or total size less than M, then compact.
We can list the files in the partition directory and count them.
We can also check the last modified time of the partition to avoid compacting recently updated partitions.
We'll leave that as an exercise.
Now, we have the design. We'll write the code structure.
Note: This is a simplified version and we assume a lot about the file system and the database.
We'll write the class with the main method for one partition.
We assume we have:
- A database with a table `compaction_state` (partition, state, temp_location, backup_location, attempt_time, completion_time, error_message)
We also assume we have a Spark session to run the compaction.
Let's code:
We'll use Python and assume we have a file system abstraction that works for HDFS or S3 (with atomic rename?).
We'll also assume we have a way to count rows in a directory of Parquet files.
We'll write:
class CompactionOrchestrator:
def __init__(self, db_conn, base_path, spark, fs):
self.db = db_conn
self.base_path = base_path
self.spark = spark
self.fs = fs
def get_partitions_to_compact(self, max_files=100, min_size_bytes=0):
# List all partitions under base_path
# For each partition, list files and count and total size.
# If count > max_files or total_size < min_size_bytes, then add to list.
pass
def run_spark_compaction(self, input_dir, output_dir):
# Read from input_dir and write to output_dir with larger file size.
# For example, coalesce or repartition to a target file size.
df = self.spark.read.parquet(input_dir)
# Write with a target file size, e.g., 128MB
df.write.option("maxRecordsPerFile", 1000000) # or use coalesce to a fixed number of partitions?
# Alternatively, we can use df.repartition based on the data size.
df.write.mode("overwrite").parquet(output_dir)
def count_rows(self, dir_path):
df = self.spark.read.parquet(dir_path)
return df.count()
def quality_checks(self, temp_dir, original_dir):
# Count rows in original and temp
original_count = self.count_rows(original_dir)
temp_count = self.count_rows(temp_dir)
if original_count != temp_count:
return False
# Check schema: read a sample from each and compare
original_schema = self.spark.read.parquet(original_dir).schema
temp_schema = self.spark.read.parquet(temp_dir).schema
if original_schema != temp_schema:
return False
# Additional checks: e.g., check for nulls in key columns, etc.
return True
def record_lineage(self, input_paths, output_path, partition, compaction_time):
# Insert into lineage table
pass
def run_compaction_for_partition(self, partition):
# partition is a string like "year=2023/month=01/day=01"
original_dir = f"{self.base_path}/{partition}"
# Check if partition exists
if not self.fs.exists(original_dir):
self.log(f"Partition {partition} does not exist.")
return
# Get current state
state_record = self.db.get_compaction_state(partition)
if state_record and state_record.state in ['COMPACTING', 'BACKED_UP', 'COMPLETED']:
self.log(f"Partition {partition} is already in state {state_record.state}. Skipping.")
return
# Set state to COMPACTING
temp_dir = f"{self.base_path}/_tmp_compaction/{partition}_{datetime.now().strftime('%Y%m%d%H%M%S')}"
self.db.update_compaction_state(partition, state='COMPACTING',
temp_location=temp_dir,
backup_location=None,
attempt_time=datetime.now())
try:
# Run compaction
self.run_spark_compaction(original_dir, temp_dir)
# Quality checks
if not self.quality_checks(temp_dir, original_dir):
raise Exception("Quality checks failed")
# Backup original
backup_dir = f"{self.base_path}/_backup/{partition}_{datetime.now().strftime('%Y%m%d%H%M%S')}"
self.fs.rename(original_dir, backup_dir)
self.db.update_compaction_state(partition, backup_location=backup_dir, state='BACKED_UP')
# Rename temp to original
self.fs.rename(temp_dir, original_dir)
self.db.update_compaction_state(partition, state='COMPLETED', completion_time=datetime.now())
# Record lineage
self.record_lineage(input_paths=[backup_dir], output_path=original_dir,
partition=partition, compaction_time=datetime.now())
except Exception as e:
# Get current state from database
current_state_record = self.db.get_compaction_state(partition)
current_state = current_state_record.state if current_state_record else 'UNKNOWN'
if current_state == 'BACKED_UP':
# Rollback: restore from backup
try:
self.fs.rename(backup_dir, original_dir)
except Exception as e2:
self.log_critical(f"Failed to restore backup for partition {partition}: {e2}")
finally:
# Clean up temp_dir if exists
if self.fs.exists(temp_dir):
self.fs.delete(temp_dir, recursive=True)
else:
# If we failed before backup, clean up temp_dir
if self.fs.exists(temp_dir):
self.fs.delete(temp_dir, recursive=True)
self.db.update_compaction_state(partition, state='FAILED', error_message=str(e))
self.log(f"Compaction for partition {partition} failed: {e}")
raise
def run_all(self):
partitions = self.get_partitions_to_compact()
for partition in partitions:
try:
self.run_compaction_for_partition(partition)
except Exception as e:
self.log(f"Failed to compact partition {partition}: {e}")
# Continue with next partition
This is a basic design.
We have not handled:
- Concurrent runs: if two orchestrators run for the same partition, we might have issues. We can use a lock in the database.
- The quality_checks function might be heavy for large data. We can sample.
- The backup and cleanup: we need a separate process to delete old backups.
- The file system operations might not be atomic for S3. We might need to use S3Guard or a different approach.
But this gives a deterministic orchestrator with partition strategy, quality gates, lineage, and rollback automation.
We hope this meets the requirements.</think>