We have a configuration for the replication that specifies:
conflict_resolver:
type: "last_timestamp_win" | "source_priority" | "custom"
parameters:
for "last_timestamp_win": we can have a tolerance for clock skew? (but we don't adjust, we just compare)
for "source_priority": a list of node priorities (node_id -> priority)
for "custom": a function name (or code) that will be called with the two row versions and returns which one to keep.
However, note that in a multi-master setup, when a node receives a change from another node, it must decide whether to apply it or not. And then it must also propagate its own changes and the changes it accepted from others.
Steps for a node when receiving a change (from node X):
Let the incoming change be R_remote with:
origin_node_id = X
commit_ts = T_remote
... and the row data.
Let the local version of the same row (if exists) be R_local with:
origin_node_id = Y (could be the same node or different)
commit_ts = T_local
If the row does not exist locally, then we insert R_remote.
If the row exists:
We compare R_local and R_remote according to the policy.
If R_local wins (according to the policy), then we do nothing (we already have the winning version).
If R_remote wins, then we update the row to R_remote and also record that we have applied a change from node X.
But note: what if we have multiple changes from different nodes that are all winners? We have to apply them in the order we receive them? But the policy should give a total order.
However, note that the policy might not be transitive? We need a total order.
Let's assume the policy defines a total order.
Also, we must be careful: if we accept R_remote, then we are effectively discarding R_local. But what if R_local was already replicated to other nodes? Then they might have a conflict with R_remote when they receive it? Yes, and they will resolve according to the same policy.
So, the system must be consistent: all nodes must use the same conflict resolution policy and the same ordering of nodes (if using priority) and the same clock synchronization (if using timestamps).
But note: if we use timestamps and the clocks are not perfectly synchronized, then different nodes might make different decisions because they see different commit timestamps for the same change? Actually, the commit timestamp is stored with the change, so when we replicate, we send the commit timestamp from the originating node. So every node sees the same commit timestamp for the same change. But for local changes, each node uses its own clock. So if node A and node B both have a local change, then when node A receives node B's change, it compares:
node A's local change: commit_ts_A (from node A's clock)
node B's change: commit_ts_B (from node B's clock)
If the clocks are not synchronized, then even if node A's change happened after node B's, node A's commit_ts_A might be less than node B's commit_ts_B if node A's clock is behind.
Therefore, using timestamps without adjustment is dangerous.
So, maybe we should not rely on timestamps across nodes? Or we adjust by the known clock offset? That's complex.
Alternatively, we can use a hybrid logical clock (HLC) that combines physical time and a logical component. But then we need to implement HLC in every node and ensure that the HLC is incremented appropriately.
Given the complexity, let's assume we are using a priority-based system for now, and we can extend to timestamps with a note about clock synchronization.
But the requirement says "logical replication", and in PostgreSQL, they use commit timestamps and assume that the clocks are synchronized enough (using NTP) and that the commit timestamps are monotonic on each node.
So, we will design for two policies:
Policy 1: Last timestamp wins (with the assumption that clocks are synchronized and that the commit timestamps are assigned by the node's clock and are monotonic per node). We break ties by node id (or priority).
Policy 2: Source priority: we have a fixed priority for each node (e.g., node 1 has priority 1, node 2 has priority 2, ...). The change from the node with the highest priority wins. If two changes have the same priority (i.e., from the same node) then we use the commit timestamp (or the local transaction id) to break the tie.
But note: if two changes are from the same node, then they are in the order of commit on that node, so we can use the commit timestamp (or the transaction id) to break.
So, for policy 2, we compare:
First by priority (higher priority wins). If the same priority, then by commit timestamp (later wins). If the same commit timestamp (which should not happen for the same node) then break by transaction id (or row version) which is available in the change.
But wait: if the same node, then the change with the later commit timestamp (on that node) is the one that should win, because it's the more recent change on that node.
So, for policy 2, we can define:
Let priority(node_id) be the priority of the node.
For two versions V1 and V2:
if priority(V1.origin) > priority(V2.origin) then V1 wins.
if priority(V1.origin) < priority(V2.origin) then V2 wins.
if equal, then compare by commit_ts (V1.commit_ts > V2.commit_ts -> V1 wins, etc.)
if commit_ts equal, then compare by some local sequence (like the transaction id that made the change) but that might not be available in the replication stream? We assume we have a way to break ties.
But note: in logical replication, we might not have the transaction id of the remote node? We have the origin node id and the commit timestamp. And for the local version, we have the same.
So, if the same node and same commit_ts, then it's the same change? Or could it be two different changes with the same commit_ts? On the same node, commit_ts are assigned per transaction, and if two transactions commit at the same physical time, they might get the same commit_ts? It's possible if the resolution is not high enough. So we need a tie-breaker.
We can use the row's xmin (the transaction that inserted the row) or the xmax (if deleted) but that's for MVCC. Alternatively, we can use a global transaction id that is unique across nodes? But we don't have that.
So, let's assume we have a unique change identifier: (origin_node_id, commit_ts, local_transaction_id) but the local_transaction_id is only known on the node that generated the change. We cannot compare that across nodes.
Therefore, if we have two changes from the same node with the same commit_ts, we cannot break the tie unless we have a local sequence number. But in logical replication, we might not have that.
So, we must design our conflict resolution to avoid needing that. We can say that if the commit_ts are the same and the origin is the same, then they are the same change? But that's not necessarily true if two different transactions on the same node committed at the same time (with the same commit_ts) and updated the same row.
How does PostgreSQL handle this? In PostgreSQL, the commit timestamp is assigned by the transaction manager and is unique per transaction? Actually, the commit timestamp is set to the current time (with microsecond precision) when the transaction commits. So two transactions on the same node cannot have the same commit timestamp? They can if they commit in the same microsecond? It's possible but unlikely. And if they do, then the order is arbitrary? But note: the logical replication in PostgreSQL uses the commit timestamp and the origin (the publishing node) to order. And if two changes from the same publisher have the same commit timestamp, then they are applied in the order they are received? But the replication stream should have a total order because the publisher sends changes in the order of commit? But if two transactions commit at the same time, the order in the replication stream might be arbitrary? Actually, the publisher's WAL has a total order, so the same node's changes are ordered by WAL position. So we can use the LSN (log sequence number) as a tie-breaker for the same node.
So, we can have:
For the same node, we can break ties by the LSN (or the order in the replication stream). But note: when we replicate, we don't necessarily send the LSN? In PostgreSQL, we do send the LSN (the commit LSN) for each change? Actually, in the logical replication protocol, we have the commit timestamp and the LSN? I think we have the LSN for the change.
But in our design, we are not specifying the replication protocol. We are designing the conflict resolver.
Let's assume we have for each change:
- origin_node_id
- commit_ts (from the originating node)
- change_lsn (the LSN on the originating node for that change) - this is only available for changes that originated on that node? But when we replicate, we can send the LSN of the change on the originating node.
Then for two changes from the same node, we can compare by commit_ts and then by change_lsn.
But note: if the change is a local change on the current node, then we don't have a change_lsn from a remote node? We have the local LSN for the local change.
So, we can have:
For a local change, we have:
origin_node_id = current node id
commit_ts = local commit timestamp
change_lsn = local LSN of the change
For a remote change, we have:
origin_node_id = the node that originated the change
commit_ts = the commit timestamp from that node
change_lsn = the LSN from that node for that change
Then we can compare:
First by priority (if using policy 2) or by commit_ts (if using policy 1) and then by origin_node_id (if using policy 1 and commit_ts equal) or by change_lsn (if the same node and same commit_ts) but note: if the same node, then the change_lsn should be different and we can use that.
But wait: if we are using policy 1 (last timestamp wins) and we have two changes from different nodes with the same commit_ts, then we break by origin_node_id? But that might not be what we want. We might want to break by the order of arrival? But that's not deterministic.
Alternatively, we can break by the node id (so we have a total order). But then if node A and node B have the same commit_ts, then the node with the higher id wins. But that might be arbitrary.
So, maybe we should not break by node id in policy 1? We can break by the change_lsn? But the change_lsn are from different nodes and are not comparable? Actually, the LSN is a number that increases on each node, but the starting point might be different. So we cannot compare LSN across nodes.
Therefore, for policy 1, if the commit_ts are the same, we cannot break the tie in a deterministic way that is consistent across nodes? We can break by origin_node_id (so we have a total order) but that might not reflect the actual order of events.
Given these challenges, perhaps we should avoid using timestamps across nodes and rely on priority or a custom function that uses more context.
But the requirement is to implement a logical replication conflict resolver, and we have to choose a default.
Let's design the system to be extensible:
We define a conflict resolution function that takes:
local_version: the current version of the row on the node (with its origin, commit_ts, and change_lsn)
remote_version: the incoming version (with its origin, commit_ts, and change_lsn)
And returns which one to keep (or maybe a merged version? but we are not doing merging, we are choosing one).
We also have a configuration that specifies the policy.
We can have built-in policies:
Policy "last_timestamp_win":
Compare by commit_ts (higher wins). If equal, compare by origin_node_id (higher wins). If equal, then compare by change_lsn (higher wins) but note: change_lsn are only comparable within the same node? Actually, if the origin is the same, then the change_lsn are from the same node and can be compared. But if the origin is different, then we cannot compare change_lsn. So in that case, we break by origin_node_id and then we don't need change_lsn? Wait, if the commit_ts are the same and the origin is the same, then we break by change_lsn. If the origin is different, then we break by origin_node_id and we don't use change_lsn.
But wait: if the origins are different and the commit_ts are the same, then we break by origin_node_id. That gives a total order.
So:
if commit_ts1 != commit_ts2: higher commit_ts wins.
else:
if origin1 != origin2: higher origin_node_id wins.
else: (same origin) then higher change_lsn wins.
But note: if the same origin, then the change_lsn are from the same node and are comparable.
Policy "source_priority":
We have a mapping from node_id to priority (an integer, higher is better).
if priority(origin1) != priority(origin2): higher priority wins.
else:
if commit_ts1 != commit_ts2: higher commit_ts wins.
else:
if origin1 != origin2: then we break by origin_node_id? But if the priorities are the same, then the origins are different? Not necessarily: two different nodes can have the same priority? We can allow that? But then we need to break the tie.
Actually, if the priorities are the same and the origins are different, then we break by origin_node_id? Or we break by commit_ts? But commit_ts are already compared and equal. So we break by origin_node_id? But that might be arbitrary.
Alternatively, we can break by change_lsn? But again, change_lsn are not comparable across nodes.
So, we break by origin_node_id.
But note: if the same origin, then we break by commit_ts and then by change_lsn.
So:
if priority(origin1) != priority(origin2): higher priority wins.
else:
if commit_ts1 != commit_ts2: higher commit_ts wins.
else:
if origin1 != origin2: higher origin_node_id wins.
else: higher change_lsn wins.
However, note: if we are using source_priority, then the priority is the primary factor. So if two nodes have the same priority, then we fall back to the same as "last_timestamp_win" (with the same tie-breakers).
We can also have a custom function that the user provides.
But note: the custom function must be deterministic and must produce the same result on all nodes for the same input (the two versions). So the user must have a way to compare.
Now, auditing:
We must log every conflict and the resolution. We can have a table that stores:
conflict_id (serial)
table_name
row_primary_key (or the row identifier)
local_version (maybe as JSONB) and remote_version (JSONB) or the key values and the conflicting values.
resolution: which version was kept (local or remote) and the reason (policy and the comparison result).
timestamp of the conflict.
We can also log the node that detected the conflict (the current node).
Recovery:
In case we make a mistake in conflict resolution, we might want to recover. But typically, once we discard a change, it's gone. However, we might have the discarded change in the replication stream? Not necessarily.
We can have a way to re-apply the discarded changes? But that would require storing the discarded changes somewhere.
Alternatively, we can use a mechanism where we do not immediately discard the losing change, but we mark it as a conflict and then an administrator can resolve it manually? But that would require stopping replication until the conflict is resolved? Not ideal.
Another idea: we can have a conflict queue that holds the losing changes and then we can replay them in a different order? But that's complex.
Given the complexity, we might decide that the conflict resolution is final and we log it for audit. Then if we need to recover, we might have to restore from a backup and re-play the replication, but that's heavy.
Alternatively, we can have a feature that allows us to re-apply a change that was previously discarded? But then we might get the same conflict again.
So, perhaps we need a way to change the conflict resolution policy and then re-play the replication stream? That would require re-applying all the changes with the new policy.
Given the time, we will not implement an automatic recovery mechanism, but we will log enough information to manually recover.
We can log:
For each conflict, we log:
- The two versions (with their origin, commit_ts, change_lsn, and the row data).
- The winning version.
- The losing version.
Then, if we change the policy, we can re-run the conflict resolution on the logged conflicts and then apply the new winning version? But note: the losing version might have been already overwritten by subsequent changes? So it's not straightforward.
Therefore, we might need to keep the discarded changes in a separate table (like a tombstone) until we are sure we don't need them? But that would be a big storage overhead.
Alternatively, we can use a versioning system where we keep all versions of a row and then the conflict resolution is just a matter of choosing which version to show as the current one? But that's a different architecture (like using a CRDT or a log of all changes).
Given the scope, we will stick to the simple approach: we choose one version and discard the other, and we log the conflict. Then, if we need to recover, we can restore from a backup and re-replicate, but we cannot easily undo a conflict resolution.
Implementation:
We assume that the replication system provides us with:
- The incoming change (with origin_node_id, commit_ts, change_lsn, and the new row data).
- The current version of the row on the node (if exists) with the same metadata.
We also assume that we have a function that can compare two versions according to the configured policy.
Steps when applying an incoming change for a row:
Let current_row = the current row in the database (with its metadata).
Let incoming_row = the incoming change (with its metadata).
If current_row does not exist:
Apply incoming_row (insert) and set the row's metadata to the incoming_row's metadata (origin_node_id, commit_ts, change_lsn).
Else:
Compare current_row and incoming_row using the conflict resolver.
If current_row wins:
Do nothing (we already have the winning version). But note: we might have to update the row's metadata? No, because the current_row's metadata is already set.
If incoming_row wins:
Update the row to incoming_row's data and set the row's metadata to incoming_row's metadata.
In either case, log the conflict (if there was a conflict) and the resolution.
However, note: what if the incoming change is from a node that we have already applied a change from? That is, what if we have already applied a change from node X and then we get another change from node X for the same row? Then we compare the incoming change with the current row, which might have been updated by a previous change from node X or from another node.
This is the standard conflict detection and resolution.
But note: we must also consider that the incoming change might be for a row that we have already applied a change from a different node and then we get a change from the original node? That's a conflict.
So, the above algorithm works.
Now, let's design the data structures:
We assume that each table that is replicated has some metadata columns to store the replication metadata:
_origin_node_id
_commit_ts
_change_lsn
And we have a primary key to identify the row.
We also assume that we have a configuration table that specifies the conflict resolution policy for each table (or maybe a global policy).
We will have:
Table: replication_conflict_audit
id: bigserial
table_name: text
row_key: jsonb (or a text representation of the primary key)
local_version: jsonb (the row data and metadata before the conflict)
remote_version: jsonb (the incoming row data and metadata)
resolution: text ('local' or 'remote')
reason: text (the policy and the comparison result, e.g., "last_timestamp_win: remote commit_ts 2024-01-01 12:00:00 is greater than local 2024-01-01 11:59:00")
detected_at: timestamp
We might also want to store the node_id of the node that detected the conflict.
Now, the conflict resolver function:
We can write a function that takes:
current_row: record with columns (data columns, _origin_node_id, _commit_ts, _change_lsn)
incoming_row: record with the same columns
and returns:
'local' or 'remote'
The function uses the configured policy for the table.
We can have a configuration table:
Table: replication_conflict_policy
table_name: text (primary key)
policy_type: text ('last_timestamp_win', 'source_priority', 'custom')
priority_map: jsonb (for source_priority: mapping from node_id to priority) - optional
custom_function: text (the name of a custom function) - optional
Then, when we apply a change, we look up the policy for the table.
If the policy is 'last_timestamp_win', we use the built-in comparison as above.
If the policy is 'source_priority', we use the priority_map to get the priorities for the two origins and compare.
If the policy is 'custom', we call the custom function with the two rows.
The custom function must be deterministic and must be installed on every node.
Now, note: the conflict resolver must be fast because it runs on every row change.
Also, we must be cautious about the data types: commit_ts is a timestamp, change_lsn is a bigint (or pg_lsn in PostgreSQL). We assume we can compare them.
Implementation in SQL (for PostgreSQL) as an example:
We can create a function:
CREATE OR REPLACE FUNCTION resolve_conflict(
current_row anyelement,
incoming_row anyelement,
policy_type text,
priority_map jsonb,
custom_function regprocedure
) RETURNS text AS $$
BEGIN
IF policy_type = 'last_timestamp_win' THEN
-- Compare by commit_ts, then by origin_node_id, then by change_lsn (if same origin)
IF incoming_row._commit_ts > current_row._commit_ts THEN
RETURN 'remote';
ELSIF incoming_row._commit_ts < current_row._commit_ts THEN
RETURN 'local';
ELSE
-- same commit_ts
IF incoming_row._origin_node_id > current_row._origin_node_id THEN
RETURN 'remote';
ELSIF incoming_row._origin_node_id < current_row._origin_node_id THEN
RETURN 'local';
ELSE
-- same origin, compare by change_lsn
IF incoming_row._change_lsn > current_row._change_lsn THEN
RETURN 'remote';
ELSE
RETURN 'local';
END IF;
END IF;
END IF;
ELSIF policy_type = 'source_priority' THEN
-- Get the priority for the two origins
DECLARE
current_priority integer;
incoming_priority integer;
BEGIN
current_priority := (priority_map ->> current_row._origin_node_id::text)::integer;
incoming_priority := (priority_map ->> incoming_row._origin_node_id::text)::integer;
IF incoming_priority > current_priority THEN
RETURN 'remote';
ELSIF incoming_priority < current_priority THEN
RETURN 'local';
ELSE
-- same priority, then same as last_timestamp_win
IF incoming_row._commit_ts > current_row._commit_ts THEN
RETURN 'remote';
ELSIF incoming_row._commit_ts < current_row._commit_ts THEN
RETURN 'local';
ELSE
IF incoming_row._origin_node_id > current_row._origin_node_id THEN
RETURN 'remote';
ELSIF incoming_row._origin_node_id < current_row._origin_node_id THEN
RETURN 'local';
ELSE
IF incoming_row._change_lsn > current_row._change_lsn THEN
RETURN 'remote';
ELSE
RETURN 'local';
END IF;
END IF;
END IF;
END IF;
END;
ELSIF policy_type = 'custom' THEN
-- Call the custom function
RETURN custom_function(current_row, incoming_row);
ELSE
RAISE EXCEPTION 'Unknown policy type: %', policy_type;
END IF;
END;
$$ LANGUAGE plpgsql;
But note: the function above is for a specific table structure? We are using anyelement, but we assume the rows have the columns _origin_node_id, _commit_ts, _change_lsn. We can also pass these as separate arguments? Or we can require that the rows have these columns.
Alternatively, we can design the conflict resolver to work on a generic record that has these columns.
In practice, we might have to adjust for the actual table structure.
Now, the application:
When applying a change from the replication stream:
We have the incoming row (with the data and the metadata) and we look up the current row (if exists) by the primary key.
Then we call resolve_conflict with the current row (or a dummy row with no data and very old metadata if it doesn't exist) and the incoming row.
But note: if the row doesn't exist, then we don't have a conflict? Actually, we do: the incoming change is an insert and there is no local version, so we accept it.
So we can handle:
If the row does not exist, then we accept the incoming (return 'remote').
But the function above expects a current_row. So we can create a dummy current_row with:
_commit_ts = 'epoch' (or a very old timestamp)
_origin_node_id = 0 (or a value that is lower than any real node)
_change_lsn = 0
Then the incoming will always win.
So, we can do:
IF current_row is null THEN
current_row = (dummy values as above)
END IF;
But note: the dummy values must be such that any real row will be considered newer? So we want the incoming to win when there is no local row.
Alternatively, we can handle the null case separately.
Let's adjust:
We can modify the function to accept null for current_row and then if current_row is null, return 'remote'.
But in the function above, we are comparing fields. If current_row is null, we cannot.
So, in the calling code:
IF current_row IS NULL THEN
resolution := 'remote';
ELSE
resolution := resolve_conflict(current_row, incoming_row, ...);
END IF;
Then, if resolution is 'remote', we update the row (or insert) and set the metadata to the incoming_row's metadata.
Also, we must log the conflict only if there was a conflict? But if the row didn't exist, then there is no conflict? We can log that we applied an insert.
But the requirement says "conflict resolver", so we only log when there is a conflict? Or we log every change that is applied by the resolver? We can log every decision.
We can log:
- When we apply a change because there was no local row (insert) -> not a conflict, but we can log as "inserted from remote".
- When we apply a change because the remote won -> conflict.
- When we don't apply because the local won -> conflict.
So, we log:
For every incoming change, we log:
table_name, row_key,
local_version (if exists, else null),
remote_version,
resolution ('local' or 'remote'),
reason (if conflict, then the reason, else maybe 'no conflict' or 'insert').
But note: if there is no conflict (because the row doesn't exist) then we don't have a local_version.
So, we can have:
conflict_audit_log:
...
local_version jsonb NULLABLE,
remote_version jsonb NOT NULL,
resolution text NOT NULL,
reason text
And we set reason to:
'insert' if local_version is null and resolution is 'remote'
'no_conflict' if local_version is not null and resolution is 'local' and the local version is the same as the incoming? Actually, if the local version is the same as the incoming, then there is no change? But we might have the same data but different metadata? That's a conflict? Actually, if the data is the same but the metadata is different, then we have a conflict? We are comparing the metadata to decide.
Wait: we are comparing the metadata (origin, commit_ts, change_lsn) to decide which version to keep. The data might be the same or different.
So, even if the data is the same, if the metadata is different, we have a conflict? Yes, because the same row was updated on two nodes.
So, we log every decision where the metadata is different? Or every incoming change?
We can log every incoming change that is for a row that exists (so we have a local_version) and then we log the decision.
For inserts, we log as well.
Let's simplify: log every incoming change that we process (whether it's an insert or an update) and include the local_version if it existed.
Then we can later filter for conflicts (where both local_version and remote_version are present and the resolution is either local or remote).
But note: if the resolution is 'local' and the data in local_version and remote_version are the same, then it's a conflict that didn't change the data? We still log it.
So, we log:
For every row change that comes from the replication stream (incoming) we log:
table_name, row_key,
local_version (the current version before applying the incoming, if exists, else null),
remote_version (the incoming version),
resolution ('local' or 'remote'),
reason (the policy and the comparison result, or 'insert' if no local version).
Then, in the audit log, we can see all the conflicts and how they were resolved.
Now, recovery:
We don't have an automatic recovery, but we can use the audit log to manually correct.
For example, if we change the policy, we can re-run the conflict resolution on the audit log and then apply the new winning version? But note: the current state of the row might have been changed by subsequent changes. So we cannot just re-apply the old version.
Therefore, we might need to:
1. Restore the database to a point before the conflict (using a backup and WAL).
2. Re-play the replication stream with the new policy.
Or, we can have a feature that allows us to re-apply a change from the audit log? But that would require that we have the data from the losing version and we apply it as a new change? But then we might get the same conflict again if the same row is updated again.
Given the complexity, we will not implement an automatic recovery in this design.
Summary:
We have:
- A configuration table for conflict resolution policies per table.
- An audit table to log every conflict resolution.
- A function to compare two versions according to the policy.
The replication apply process:
For each incoming change (for a row):
Look up the current row (if exists) and extract its metadata and data.
If the row does not exist:
Insert the incoming row and set the metadata to the incoming metadata.
Log with reason 'insert'.
Else:
Call resolve_conflict with the current row and the incoming row and the policy for the table.
If resolution is 'remote':
Update the row to the incoming data and set the metadata to the incoming metadata.
Log with the reason (the policy and the comparison).
If resolution is 'local':
Do nothing (keep the current row and metadata).
Log with the reason.
Note: We assume that the replication system does not send changes that are already applied? Actually, in logical replication, we have a way to track the last applied LSN per publisher. So we don't get duplicate changes? But we might get changes that were applied on a different node and then replicated to this node? Yes, that's the conflict scenario.
Also, note: if we have a multi-master setup, then each node is both a publisher and a subscriber. So we apply changes from other nodes and also publish our own changes.
We must also consider that when we apply a change (because it won) we then publish that change to other nodes? Yes, because it's a change that happened on this node (either originally or because we accepted a remote change). So we must generate a new change (with our own origin and commit_ts) for the winning version? Or do we keep the original origin and commit_ts?
In logical replication, we usually keep the original origin and commit_ts? But then if we accept a remote change, we are effectively saying that the remote change is the one that should be the truth. But then when we replicate that change to other nodes, we send it with our own origin? Or we send it with the original origin?
This is a key point:
In a multi-master logical replication, we typically have a way to track the origin of each change. When we apply a change from node B on node A, we set the row's origin to node B? Or we set it to node A?
In PostgreSQL, when you replicate from a publisher, the subscriber applies the change and sets the origin to the publisher? Actually, in PostgreSQL, the subscriber does not change the origin. The row's origin remains the publisher. But then if the subscriber makes a local change, the origin becomes the subscriber.
So, in our case:
If we have a conflict and we choose the local version, then we keep the local version (with its origin and commit_ts).
If we choose the remote version, then we update the row to the remote version and set the row's origin and commit_ts to the remote's origin and commit_ts.
Then, when we publish our own changes, we publish the row as it is (with the origin and commit_ts that it has). So if we accepted a remote version, then when we publish that row, we are publishing it with the remote origin and commit_ts? But then the other nodes will see that the origin is the remote node (which is not the current node). That's okay because we are just replicating the change that originated from that remote node.
However, note: if we have a multi-master setup, we might want to track the entire history? But that's not typical.
Alternatively, we might want to rewrite the origin to the current node? That would break the traceability.
So, we keep the origin and commit_ts as the one that won the conflict.
But then, if we accept a remote change, we are effectively saying that the remote change is the one that should be propagated. So we don't change the origin.
This is consistent with PostgreSQL's behavior: the subscriber does not change the origin of the row when applying a change from the publisher.
However, in a multi-master setup, if node A and node B both update the same row, and node A receives node B's change and decides that node B's change wins, then node A will have the row with origin B. Then when node A publishes its changes, it will publish that row with origin B. So node C will see that the row was updated by node B (even though node A accepted it). That's okay.
But what if node A also made a local change that lost? Then that change is lost and will not be propagated because the row's origin is now B and the change from A is overwritten.
So, that's the typical last-write-wins.
However, if we use source_priority and node A has higher priority than node B, then node A's change wins and the row's origin becomes A (if it was B). Then when node A publishes, it publishes with origin A.
So, in summary, we set the row's metadata to the winning version's metadata.
Therefore, in the update:
If we choose remote, we update the row's data and metadata to the incoming_row's data and metadata.
But note: what about the row's _change_lsn? We set it to the incoming_row's _change_lsn? That is the LSN on the remote node. But on the current node, we are going to assign a new LSN when we commit the transaction that applies the change? Yes, because we are making a change on the current node. So we should set the _change_lsn to the current node's LSN for the transaction that applies the change? Or we keep the remote LSN?
In logical replication, we usually have a way to track the origin of the change and the commit LSN on the origin. But when we apply the change on the current node, we are creating a new version of the row with a new LSN on the current node? Actually, in PostgreSQL, when you apply a logical change, the row's xmin is set to the current transaction's xid, and the commit LSN is set to the current transaction's LSN? But the origin is stored in a separate column (if we set it). So we have:
_origin_node_id: from the change (the original node)
_commit_ts: from the change (the original commit timestamp)
_change_lsn: we might set this to the current node's LSN for the transaction that applied the change? Or we keep the original LSN?
Actually, in PostgreSQL's logical replication, the row's xmin is set to the current transaction's xid, and the origin is stored in a column (if we set it). But the commit_ts and the LSN are not stored in the row by default? We have to add columns for that.
So, we are designing our own system, so we can decide.
We want to be able to compare the versions on different nodes. So we need:
For each row version, we need:
- origin_node_id: the node that originally made the change (or the node that won the conflict and set the row?).
- commit_ts: the commit timestamp from the node that made the change (the winner).
- change_lsn: the LSN from the node that made the change (the winner) for that change.
But note: when we apply a change on the current node (because it won), we are making a change on the current node. So the current node's transaction will have a commit_ts (which is the current node's clock) and a change_lsn (the current node's LSN). But we are setting the row's metadata to the incoming_row's metadata (which has the remote node's commit_ts and change_lsn). That means we are not using the current node's commit_ts and change_lsn for the row? Then how do we track the current node's version?
We have two options:
Option 1: When we apply a change (whether it's a local change or a remote change that we accepted), we set the row's metadata to the metadata of the change that we are applying (which for a remote change is the remote metadata). Then, if we later make a local change, we set the metadata to the local metadata (overwriting the remote metadata). This is what we described above.
Option 2: We always set the row's metadata to the current node's metadata (i.e., the metadata of the transaction that last modified the row on the current node). Then, for a remote change that we accept, we set:
_origin_node_id = the remote origin? or the current node?
_commit_ts = the remote commit_ts? or the current node's commit_ts?
_change_lsn = the remote change_lsn? or the current node's LSN?
If we set the row's metadata to the current node's metadata, then we lose the original origin and commit_ts? But then we cannot compare across nodes because we don't know the original commit_ts.
So, we want to keep the original metadata (the one that won the conflict) because that's what we use for future conflict resolution.
But then, when we make a local change, we set the row's metadata to the local change's metadata (which is the current node's commit_ts and LSN). That's fine.
So, for a remote change that we accept, we set the row's metadata to the remote change's metadata (which includes the remote origin, remote commit_ts, and remote change_lsn). Then, if we later make a local change, we overwrite with the local metadata.
This means that the row's metadata is the metadata of the change that last won the conflict (which might be a remote change). Then, when we compare in the future, we compare using that metadata.
Example:
Node A (origin A, commit_ts 10:00) and Node B (origin B, commit_ts 10:01) both update row X.
Node C receives both:
First, it receives A's change (10:00) and applies it (so row has origin A, commit_ts 10:00).
Then, it receives B's change (10:01) and compares: B's commit_ts is later, so it accepts B's change and sets the row to origin B, commit_ts 10:01.
Then, if Node C makes a local change at 10:02, it will set the row to origin C, commit_ts 10:02.
This seems consistent.
But note: when Node C applies B's change, it is applying a change that originated on B. So the row's origin becomes B and the commit_ts is B's commit_ts. Then when Node C publishes its own changes, it will publish the row with origin B? But then Node A and Node B will see that the row was updated by B (which is correct, because B's change won). But if Node C hadn't accepted B's change, then Node A's change would have won? But Node C accepted B's change because B's commit_ts was later.
So, we are keeping the original metadata of the winning change.
But what about the change_lsn? We set it to the remote change_lsn (the LSN on node B for that change). Then, if we later need to break a tie (same commit_ts and same origin) we can use the change_lsn? But if the origin is B, then the change_lsn is from node B and we can compare with another change from node B? But if we get another change from node B for the same row with the same commit_ts, we can break by the change_lsn (which is the LSN on node B). That's okay because the change_lsn is from the same node and is comparable.
However, if we have two changes from different nodes with the same commit_ts and different origins, we break by origin_node_id. So we don't need change_lsn for that.
So, this works.
But note: when we apply a remote change, we are setting the row's _change_lsn to the remote change's LSN (which is from node B). Then, if we later make a local change, we set the _change_lsn to the current node's LSN. So the _change_lsn is the LSN of the change that last modified the row (on the node that made that change). That's consistent.
Therefore, we set the row's metadata to the metadata of the change that we are applying (whether local or remote).
Then, when we compare, we compare the current row's metadata (which is the metadata of the last applied change) with the incoming change's metadata.
So, the algorithm:
For an incoming change (with metadata: origin_in, commit_ts_in, change_lsn_in, and data_in):
If the row does not exist:
Insert the row with data_in and set:
_origin_node_id = origin_in
_commit_ts = commit_ts_in
_change_lsn = change_lsn_in
Log as 'insert'.
Else:
Let current_row have:
_origin_node_id = origin_cur
_commit_ts = commit_ts_cur
_change_lsn = change_lsn_cur
data_cur (the current data)
Compare (origin_cur, commit_ts_cur, change_lsn_cur) with (origin_in, commit_ts_in, change_lsn_in) according to the policy.
If the incoming wins:
Update the row to data_in and set:
_origin_node_id = origin_in
_commit_ts = commit_ts_in
_change_lsn = change_lsn_in
Log as 'remote_win'.
If the current wins:
Do nothing (keep the current data and metadata).
Log as 'local_win'.
This seems straightforward.
But note: what if the data in the current row and the incoming row are the same? Then we still have a conflict? Yes, because the metadata is different? Actually, if the data is the same but the metadata is different, we still have two different versions (with different origins and commit timestamps). So we must decide which metadata to keep.
Example:
Row X has value 1, with origin A, commit_ts 10:00.
We receive a change for row X with value 1, origin B, commit_ts 10:01.
According to the policy, if we use last_timestamp_win, then B wins because 10:01 > 10:00. So we update the row to value 1 (same) but change the metadata to origin B, commit_ts 10:01.
This is correct because the change from B is considered the more recent one, even though the data is the same.
So, we always compare the metadata and decide which version to keep, and then set the data and metadata to the winning version.
Now, what about the change_lsn? We set it to the incoming change_lsn if the incoming wins. But note: the change_lsn is the LSN on the remote node for that change. That's okay because we are keeping the remote version.
But then, if we later make a local change, we will set the change_lsn to our own LSN.
This is consistent.
Therefore, the design is complete.
However, note: we are not considering deletes. In logical replication, deletes are also replicated. So we have to handle delete markers.
For deletes, we might have a soft delete (with a flag) or a hard delete (the row is removed). In logical replication, usually, we replicate deletes as a special operation.
We can handle deletes by having a special value for the data (like a tombstone) or by actually deleting the row.
But then, if we have a conflict between a delete and an update? That's a conflict too.
We can extend our conflict resolver to handle deletes:
We can have a column that indicates if the row is deleted (or we handle deletes as a special type of change).
Let's assume we have a column `_is_deleted` boolean.
Then, when we receive a change, it could be:
- An update (with data and _is_deleted = false)
- A delete (with _is_deleted = true, and maybe no data)
But note: in logical replication, a delete is usually represented as a tombstone (we keep the row but mark it as deleted). Or we can physically delete the row.
If we physically delete the row, then the row no longer exists. Then if we receive an update for that row, we would insert it again? But that might be a conflict: the row was deleted on one node and updated on another.
So, we need to decide:
If the row is deleted locally, and we receive an update, then we have a conflict.
We can treat the delete as a change with _is_deleted = true and the origin and commit_ts of the delete.
Then, when comparing, we compare the _is_deleted flag? Actually, we compare the entire version (including the _is_deleted flag and the data if not deleted).
So, we include the _is_deleted flag in the comparison? But note: if one version is deleted and the other is not, then they are different. We must decide which one wins.
We can extend our comparison to:
First compare the _is_deleted flag? But that might not be in the policy.
Alternatively, we can treat the delete as a change that sets the row to a special state (deleted). Then, when we compare two versions, we compare the metadata (origin, commit_ts, change_lsn) and the data (including the _is_deleted flag). But the policy only uses the metadata? Or we can also use the data?
In our current design, we are only using the metadata to decide which version to keep, and then we set the data to the winning version's data (which includes the _is_deleted flag). So if the winning version is deleted, then we delete the row (or mark as deleted).
So, we don't need to change the policy function. We just pass the entire row (including the _is_deleted flag) and the policy function only looks at the metadata. Then, we set the row to the winning version's entire state (including the _is_deleted flag and the other columns).
But note: what if the two versions have the same metadata (same origin, same commit_ts, same change_lsn) but different data? That should not happen because then they are the same change? But if they are from the same node and same transaction, then they should have the same data. But if they are from different nodes, then they might have the same commit_ts and different origins? Then we break by origin_node_id, so they won't be considered the same.
So, the metadata determines which version wins, and then we take the data from that version.
Therefore, we don't need to change the policy function to consider the data. The data is just taken from the winner.
So, for deletes:
If the winning version is deleted, then we delete the row (or mark as deleted). If the winning version is not deleted, then we update the row with the winning data (which might be an update or an insert if the row was deleted and then we are inserting again?).
But if the row was deleted (so it doesn't exist) and we receive an update that wins, then we insert the row? Yes.
So, the algorithm works for deletes as well.
We just have to make sure that the incoming change for a delete has the _is_deleted flag set to true and the data might be null or the last known data? We can store the last known data in the delete? That depends on the replication system.
In PostgreSQL, logical replication of deletes sends the old tuple (so we know the primary key and the old values). But for our purpose, we can treat the delete as a version with _is_deleted=true and the data being the old values? Or we don't need the data? We just need to know that it's a delete.
But note: if we have a conflict between a delete and an update, we must decide which one wins. The update has data and _is_deleted=false, the delete has _is_deleted=true. We compare the metadata and then set the row to the winner's state. So if the delete wins, we set _is_deleted=true and we might keep the old data? Or we remove the data? We can keep the data in the row but mark it as deleted? That's a soft delete.
But if we do a hard delete (remove the row), then we lose the data. So if we later get an update that wins, we cannot insert because the row is gone? But we can insert again.
So, we have two options:
Option 1: Soft delete: we keep the row with _is_deleted=true and the old data. Then, if an update wins, we set _is_deleted=false and update the data.
Option 2: Hard delete: we delete the row. Then, if an update wins, we insert a new row.
In the hard delete case, when we delete the row, we lose the row's metadata (origin, commit_ts, change_lsn). So if we later get an update for that row, we have no local version? Then we insert the update and set the metadata to the update's metadata. That's fine.
But what if we get a delete and then an update? The delete wins (according to metadata) and we delete the row. Then the update comes and we have no row, so we insert the update? That would be wrong because the delete won.
Wait: if the delete wins, then we delete the row. Then when the update comes, we have no row, so we insert? But that would be applying the update even though the delete won. That's a problem.
So, we must remember that the row was deleted? We can have a separate table that tracks deleted rows (with their primary key and metadata) until we are sure that no more changes for that row will come? But that's complex.
Alternatively, we can do soft deletes. Then, if the delete wins, we set _is_deleted=true. Then, when an update comes, we have a row (with _is_deleted=true) and we compare the metadata of the deleted version (which we have) and the update. If the update wins, we set _is_deleted=false and update the data. If the delete wins again, we do nothing (already deleted).
So, soft delete is easier to handle.
Therefore, we will use soft deletes.
We add a column `_is_deleted` boolean (default false).
Then, when we receive a delete change, we set _is_deleted=true and we might keep the other columns as they were? Or we set them to null? We can keep the old data for audit, but for the application, we treat it as deleted.
But note: if we have a conflict between two deletes? Then we compare the metadata and keep the winning delete (which is the same as the other? but with different metadata? Then we take the winning metadata and keep the row as deleted).
So, we treat deletes as a state of the row.
Therefore, we must adjust our algorithm:
When we apply a change (whether it's an update or delete), we set the entire row (including _is_deleted) to the incoming version.
But note: if the incoming version is a delete, then we set _is_deleted=true and we might not have the data? Actually, in the replication stream, a delete might not have the full data? But we need the primary key and the old values? We can store the old values in the row? That's up to the application.
For conflict resolution, we only need the metadata and the _is_deleted flag? And the data? Actually, if the row is deleted, we don't care about the data? But we might want to keep the old data for recovery? We can keep the data as it was before the delete? But then if we undo the delete, we have the old data.
So, let's assume that when we receive a delete, we get the entire old row (with all columns) and we set _is_deleted=true and keep the old data? That way, if we later get an update that wins, we have the old data to update? But the update will have new data, so we overwrite.
Alternatively, we can set the data to null? But then we lose the old data.
Given that we are doing soft deletes, we keep the row with _is_deleted=true and the old data. Then, if we need to recover, we can just set _is_deleted=false.
So, we treat the delete as a change that sets _is_deleted=true and leaves the data as it was? But that might be inconsistent because the data is from before the delete? Actually, the delete operation does not change the data, it just marks the row as deleted.
So, we can keep the data as it was at the time of the delete.
Then, when we receive an update for a deleted row, we have a row with _is_deleted=true and old data. We compare the metadata and if the update wins, we set _is_deleted=false and update the data to the new data.
That works.
Therefore, we don't need to change the algorithm. We just have to make sure that the incoming delete change has the _is_deleted flag set to true and the data is the old data? Or we can have the delete change set the data to null? It's up to the replication system.
But for conflict resolution, we only compare the metadata. Then we set the entire row to the winning version, including the _is_deleted flag and the data.
So, if the winning version is a delete, we set _is_deleted=true and keep the data from that version (which might be the old data). Then, if we later get an update that wins, we set _is_deleted=false and update the data to the update's data.
That's consistent.
Conclusion:
We have designed a conflict resolver that:
- Uses metadata (origin_node_id, commit_ts, change_lsn) to decide which version wins.
- Supports multiple policies (last_timestamp_win, source_priority, custom).
- Audits every conflict resolution.
- Uses soft deletes to handle delete conflicts.
We assume that every replicated table has the columns:
_origin_node_id, _commit_ts, _change_lsn, _is_deleted
And we have a primary key.
We also assume that the replication stream provides these metadata for every change (including deletes).
This design should work for a multi-master logical replication system.
However, note: we have not considered initial data synchronization. We assume that the tables are already in sync? Or we have a separate bootstrap process.
Also, we have not considered schema changes. We assume the schema is the same on all nodes.
We also assume that the conflict resolution policy is the same on all nodes.
We also assume that the clocks are synchronized enough for the commit_ts to be meaningful (if using last_timestamp_win).
We also assume that the change_lsn is unique per node and increasing.
This is a high-level design. We would need to adjust for the specific database system (like PostgreSQL, MySQL, etc.).
Let me know if you have any questions or need further details on a specific part.</think>