🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Thread View: linux.kernel.git
6 messages
6 total messages Started by Maciej Ciemborowicz Wed, 07 Oct 2026 18:05
[PATCH v3 0/4] refs: run copy and rename through transactions
#40
Author: Maciej Ciemborowicz
Date: Wed, 07 Oct 2026 18:05
126 lines
14712 bytes
Reference copy and rename bypass the transaction API. With files, the
reference-transaction hook sees only the source deletion; with reftable,
it sees neither endpoint. This series puts the logical ref updates and
the reflog history into ordinary transactions so hooks can observe and
reject the complete operation.

Thanks to Patrick, Junio and Karthik for their feedback. Following the
review of v2, this version uses ref_transaction_update_reflog(), the API
used by backend migration, to replay history. A new
ref_transaction_replace_reflog() operation supplies the missing ability
to discard destination history before installing the queued entries.

Changes since v2:

* Split the work into four patches: internal hook suppression, reflog
  replacement, copy/rename integration, and removal of the old callbacks.
* Remove the special copy/rename dispatch from backend prepare, finish
  and abort. Each destination points to its source update, so multiple
  copies, renames and ordinary updates can share one transaction.
* Keep the hook-suppression flag private and check it centrally in
  run_transaction_hook(). It is used for the physical packed-refs child
  transaction, whose changes the parent already reports.
* Drop the pre-lock snapshot revalidation. A preparing hook may change
  the source; prepared and committed report the value read under lock.
  Copy sources are locked but are not reported as changes to the hook.
* Stage reflog replacements during prepare. A prepared veto discards
  staging files without restoring old values over live refs or changing
  the source, destination or HEAD history.
* Add coverage for complete reflog contents, mixed transactions, hook
  vetoes, source races and failure paths, and measure the performance
  cost of replaying history.

Backend-specific work remains necessary to implement the transaction
primitives. Files stages logs beside logs/refs using unique temporary
files. For directory/file conflicts and case-only renames, it queues
the destination in packed-refs: the loose source cannot remain visible
while also making room for a loose destination lock. During finish, a
backup preserves the source log until the destination log is installed;
an installation error restores that backup. Reftable writes tombstones
for old destination entries in the same table as the replacement.

The backends' final reflog records remain distinct: files appends
old->old; reftable appends old->zero and zero->old for rename, or
zero->old for copy. Forced reftable copies do change behavior: unrelated
destination history is replaced by source history, matching files when
the source has a reflog.

Replaying history requires O(N) time and memory. Buffered staging avoids
a write system call per entry, but files rename loses its constant-time
reflog move. On macOS/arm64, with no hook configured, median milliseconds
per operation over seven samples of ten operations were:

                    entries       base        v3
  files copy             10       5.05      5.08
  files rename           10       4.88      5.26
  files copy          10000      13.20     16.11
  files rename        10000       5.09     17.09
  reftable copy          10       5.25      6.11
  reftable rename        10       5.81      6.50
  reftable copy       10000      53.39     68.06
  reftable rename     10000      43.44     54.06

Process startup is included. Copy overwrites the same destination;
rename alternates between two names. Reftable starts from a migration
of the same files fixture. Repeated operations add normal log entries
and incur normal reftable compaction. Patch 3 adds
t/perf/p1424-ref-copy-rename.sh; these measurements used a separate
monotonic-clock driver because GNU time is not installed here. The
files rename regression is a cost of this design, not just hook overhead.

Validation covered 15 relevant suites with files and reftable, including
branch, update-ref, hooks, migration, reflogs and worktree refs. The two
new suites contain 34 tests, with backend-specific skips; they also
passed with SHA-256 and AddressSanitizer/UndefinedBehaviorSanitizer.
The reflog prerequisite and main change were tested as intermediate
trees. This was not a full test-suite run or a Linux/Windows run.

Files transactions are still not crash-atomic. A later failure in
finish may leave partial ref changes, as with ordinary transactions.
The source-log backup covers an installation error, not a process crash.
Unrelated nested renames can also contend for the global packed-refs
lock.

The base is 0f8e75abeb. This series is independent of the separate
batched-deletion old-OID fix discussed elsewhere in the thread.

Original patch:
https://lore.kernel.org/git/20260920165037.88524-1-maciej.ciemborowicz@gmail.com/

The range-diff below treats the rewritten and split implementation as
four new commits, so the changes above describe the mapping from v2.

Maciej Ciemborowicz (4):
  refs: distinguish internal transactions from logical updates
  refs: support replacing reflogs in a transaction
  refs: run copy and rename through ordinary transactions
  refs: remove backend-specific copy and rename callbacks

 Documentation/githooks.adoc     |  10 +
 refs.c                          | 200 ++++++++-
 refs.h                          |  25 ++
 refs/debug.c                    |  24 --
 refs/files-backend.c            | 739 +++++++++++++++++---------------
 refs/packed-backend.c           |   2 -
 refs/refs-internal.h            |  28 +-
 refs/reftable-backend.c         | 334 ++-------------
 t/helper/test-ref-store.c       |  76 ++++
 t/perf/p1424-ref-copy-rename.sh |  48 +++
 t/t1424-ref-copy-transaction.sh | 352 +++++++++++++++
 t/t1425-reflog-transaction.sh   |  59 +++
 12 files changed, 1206 insertions(+), 691 deletions(-)
 create mode 100755 t/perf/p1424-ref-copy-rename.sh
 create mode 100755 t/t1424-ref-copy-transaction.sh
 create mode 100755 t/t1425-reflog-transaction.sh

Range-diff against v2:
1:  d852537d8c < -:  ---------- refs: run copy and rename through transactions
-:  ---------- > 1:  6d7c146e57 refs: distinguish internal transactions from logical updates
-:  ---------- > 2:  5c3ec4eb49 refs: support replacing reflogs in a transaction
-:  ---------- > 3:  77af4e809c refs: run copy and rename through ordinary transactions
-:  ---------- > 4:  83fa644fb3 refs: remove backend-specific copy and rename callbacks

base-commit: 0f8e75abebff0877cae681a3d5ff31ac47f54220
-- 
2.39.3 (Apple Git-146)
[PATCH v3 1/4] refs: distinguish internal transactions from logical updates
#42
Author: Maciej Ciemborowicz
Date: Wed, 07 Oct 2026 18:05
47 lines
9741 bytes
A ref backend may use a nested transaction to persist part of a logical
update. Provide an internal-only transaction flag so that these physical
updates can avoid reporting the same operation to reference-transaction
hooks again.

Keep the check in run_transaction_hook(), covering every hook state in
one place. The flag is deliberately not part of the public refs API.
Subsequent changes use it for packed-refs updates belonging to a copy or
rename.

Signed-off-by: Maciej Ciemborowicz <maciej.ciemborowicz@gmail.com>
---
 refs.c               | 3 +++
 refs/refs-internal.h | 3 +++
 2 files changed, 6 insertions(+)

diff --git a/refs.c b/refs.c
index 92d5df5b71..00b1b51280 100644
--- a/refs.c
+++ b/refs.c
@@ -2666,6 +2666,9 @@ static int run_transaction_hook(struct ref_transaction *transaction,
 	struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
 	int ret = 0;
 
+	if (transaction->flags & REF_TRANSACTION_FLAG_INTERNAL)
+		return 0;
+
 	strvec_push(&opt.args, state);
 
 	opt.feed_pipe = transaction_hook_feed_stdin;
diff --git a/refs/refs-internal.h b/refs/refs-internal.h
index c3ac7b556f..0b41f5fa4b 100644
--- a/refs/refs-internal.h
+++ b/refs/refs-internal.h
@@ -8,6 +8,9 @@
 struct fsck_options;
 struct ref_transaction;
 
+/* Physical updates nested in a transaction already reported to hooks. */
+#define REF_TRANSACTION_FLAG_INTERNAL (1 << 2)
+
 /*
  * Data structures and functions for the internal use of the refs
  * module. Code outside of the refs module should use only the public
-- 
2.39.3 (Apple Git-146)
[PATCH v3 2/4] refs: support replacing reflogs in a transaction
#39
Author: Maciej Ciemborowicz
Date: Wed, 07 Oct 2026 18:05
528 lines
26937 bytes
Explicit log-only updates can already recreate a reflog during
migration. Add ref_transaction_replace_reflog() to replace existing
history with these entries without changing the reference itself. Keep
its marker flag private to the refs implementation so callers cannot
attach this cross-update behavior to an ordinary ref update
accidentally.

Stage files-backend replacements in unique temporary files beside the
logs and install them only during finish. Buffer writes and order
entries by their requested index. Aborting prepare only removes staging
files. In reftable, tombstone the previous entries in the same table as
the replacement.

Do not treat a log-only entry with a null new OID as a reference
deletion: it is part of the history being replayed. Propagate read
errors instead of silently copying a partial log.

Test preservation of null-OID entries, ordering, removal, hook rejection
and duplicate replacement. This is preparation for copying and renaming
through the ordinary transaction path.

Signed-off-by: Maciej Ciemborowicz <maciej.ciemborowicz@gmail.com>
---
 refs.c                        |  34 ++++++-
 refs.h                        |   9 ++
 refs/files-backend.c          | 180 +++++++++++++++++++++++++++++++---
 refs/refs-internal.h          |   3 +
 refs/reftable-backend.c       |  10 +-
 t/helper/test-ref-store.c     |  40 ++++++++
 t/t1425-reflog-transaction.sh |  59 +++++++++++
 7 files changed, 320 insertions(+), 15 deletions(-)
 create mode 100755 t/t1425-reflog-transaction.sh

diff --git a/refs.c b/refs.c
index 00b1b51280..bf219573cd 100644
--- a/refs.c
+++ b/refs.c
@@ -1413,7 +1413,6 @@ enum ref_transaction_error ref_transaction_update(struct ref_transaction *transa
 		strbuf_addstr(err, _("refusing to force and skip creation of reflog"));
 		return REF_TRANSACTION_ERROR_GENERIC;
 	}
-
 	if (!transaction_refname_valid(refname, new_oid, flags, err))
 		return REF_TRANSACTION_ERROR_GENERIC;
 
@@ -1496,6 +1495,39 @@ int ref_transaction_update_reflog(struct ref_transaction *transaction,
 	return 0;
 }
 
+int ref_transaction_replace_reflog(struct ref_transaction *transaction,
+				    const char *refname,
+				    struct strbuf *err)
+{
+	size_t i;
+	unsigned int flags = REF_LOG_ONLY | REF_NO_DEREF |
+		REF_SKIP_CREATE_REFLOG | REF_REPLACE_REFLOG;
+
+	assert(err);
+	if (transaction->flags &
+	    (REF_TRANSACTION_FLAG_INITIAL | REF_TRANSACTION_ALLOW_FAILURE)) {
+		strbuf_addstr(err, _("reflog replacement requires an "
+				     "all-or-nothing, non-initial transaction"));
+		return REF_TRANSACTION_ERROR_GENERIC;
+	}
+	if (!transaction_refname_valid(refname, NULL, flags, err))
+		return REF_TRANSACTION_ERROR_GENERIC;
+	for (i = 0; i < transaction->nr; i++) {
+		struct ref_update *update = transaction->updates[i];
+
+		if ((update->flags & REF_REPLACE_REFLOG) &&
+		    !strcmp(update->refname, refname)) {
+			strbuf_addf(err, _("reflog replacement for '%s' already queued"),
+				    refname);
+			return REF_TRANSACTION_ERROR_NAME_CONFLICT;
+		}
+	}
+
+	ref_transaction_add_update(transaction, refname, flags,
+				   NULL, NULL, NULL, NULL, NULL, NULL, NULL);
+	return 0;
+}
+
 int ref_transaction_create(struct ref_transaction *transaction,
 			   const char *refname,
 			   const struct object_id *new_oid,
diff --git a/refs.h b/refs.h
index 9979446d15..7e80d0bdfb 100644
--- a/refs.h
+++ b/refs.h
@@ -939,6 +939,15 @@ int ref_transaction_update_reflog(struct ref_transaction *transaction,
 				  uint64_t index,
 				  struct strbuf *err);
 
+/*
+ * Replace a reference's reflog with the explicit entries added to the same
+ * transaction via ref_transaction_update_reflog(). Without such entries,
+ * remove the reflog. This operation does not change the reference itself.
+ */
+int ref_transaction_replace_reflog(struct ref_transaction *transaction,
+				    const char *refname,
+				    struct strbuf *err);
+
 /*
  * Add a reference creation to transaction. new_oid is the value that
  * the reference should have after the update; it must not be
diff --git a/refs/files-backend.c b/refs/files-backend.c
index 71628550f2..70d1ff80c4 100644
--- a/refs/files-backend.c
+++ b/refs/files-backend.c
@@ -1983,6 +1983,22 @@ static int files_create_reflog(struct ref_store *ref_store, const char *refname,
 	return 0;
 }
 
+static void format_reflog_entry(struct strbuf *sb,
+				const struct object_id *old_oid,
+				const struct object_id *new_oid,
+				const char *committer, const char *msg)
+{
+	if (!committer)
+		committer = git_committer_info(0);
+
+	strbuf_addf(sb, "%s %s %s", oid_to_hex(old_oid), oid_to_hex(new_oid), committer);
+	if (msg && *msg) {
+		strbuf_addch(sb, '\t');
+		strbuf_addstr(sb, msg);
+	}
+	strbuf_addch(sb, '\n');
+}
+
 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
 			    const struct object_id *new_oid,
 			    const char *committer, const char *msg)
@@ -1990,15 +2006,7 @@ static int log_ref_write_fd(int fd, const struct object_id *old_oid,
 	struct strbuf sb = STRBUF_INIT;
 	int ret = 0;
 
-	if (!committer)
-		committer = git_committer_info(0);
-
-	strbuf_addf(&sb, "%s %s %s", oid_to_hex(old_oid), oid_to_hex(new_oid), committer);
-	if (msg && *msg) {
-		strbuf_addch(&sb, '\t');
-		strbuf_addstr(&sb, msg);
-	}
-	strbuf_addch(&sb, '\n');
+	format_reflog_entry(&sb, old_oid, new_oid, committer, msg);
 	if (write_in_full(fd, sb.buf, sb.len) < 0)
 		ret = -1;
 	strbuf_release(&sb);
@@ -2397,6 +2405,8 @@ static int files_for_each_reflog_ent(struct ref_store *ref_store,
 
 	while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
 		ret = show_one_reflog_ent(refs, refname, &sb, fn, cb_data);
+	if (ferror(logfp))
+		ret = -1;
 	fclose(logfp);
 	strbuf_release(&sb);
 	return ret;
@@ -2665,12 +2675,120 @@ static enum ref_transaction_error check_old_oid(struct ref_update *update,
 	return REF_TRANSACTION_ERROR_INCORRECT_OLD_VALUE;
 }
 
+struct staged_reflog {
+	struct tempfile *file;
+	struct ref_update **updates;
+	size_t nr, alloc;
+};
+
 struct files_transaction_backend_data {
 	struct ref_transaction *packed_transaction;
 	int packed_refs_locked;
 	struct strmap ref_locks;
+	struct strmap reflog_files;
 };
 
+static int reflog_update_cmp(const void *a, const void *b)
+{
+	const struct ref_update *one = *(struct ref_update * const *)a;
+	const struct ref_update *two = *(struct ref_update * const *)b;
+
+	return (one->index > two->index) - (one->index < two->index);
+}
+
+static int prepare_reflog_replacements(struct files_ref_store *refs,
+				      struct ref_transaction *transaction,
+				      struct strbuf *err)
+{
+	struct files_transaction_backend_data *data = transaction->backend_data;
+	struct strbuf path = STRBUF_INIT;
+	struct strbuf contents = STRBUF_INIT;
+	struct hashmap_iter iter;
+	struct strmap_entry *entry;
+	size_t i;
+	int ret = -1;
+
+	for (i = 0; i < transaction->nr; i++) {
+		struct ref_update *update = transaction->updates[i];
+		struct staged_reflog *log;
+
+		if (!(update->flags & REF_REPLACE_REFLOG))
+			continue;
+		CALLOC_ARRAY(log, 1);
+		strmap_put(&data->reflog_files, update->refname, log);
+	}
+	for (i = 0; i < transaction->nr; i++) {
+		struct ref_update *update = transaction->updates[i];
+		struct staged_reflog *log = strmap_get(&data->reflog_files, update->refname);
+
+		if (!log || !(update->flags & REF_LOG_ONLY) ||
+		    !(update->flags & REF_HAVE_NEW))
+			continue;
+		if (!(update->flags & REF_LOG_USE_PROVIDED_OIDS)) {
+			strbuf_addf(err, "replacing reflog '%s' requires explicit OIDs",
+				    update->refname);
+			goto out;
+		}
+		ALLOC_GROW(log->updates, log->nr + 1, log->alloc);
+		log->updates[log->nr++] = update;
+	}
+	strmap_for_each_entry(&data->reflog_files, &iter, entry) {
+		struct staged_reflog *log = entry->value;
+		int fd;
+
+		if (!log->nr)
+			continue;
+		QSORT(log->updates, log->nr, reflog_update_cmp);
+		/* Keep the staging file beside the logs, which may be on another device. */
+		strbuf_reset(&path);
+		files_reflog_path(refs, &path, is_root_ref(entry->key) ?
+				 ".tmp-reflog-XXXXXX" : "refs/.tmp-reflog-XXXXXX");
+		if (safe_create_leading_directories(refs->base.repo, path.buf))
+			goto write_error;
+		log->file = mks_tempfile_m(path.buf, 0666);
+		if (!log->file)
+			goto write_error;
+		fd = get_tempfile_fd(log->file);
+		for (i = 0; i < log->nr; i++) {
+			struct ref_update *update = log->updates[i];
+
+			format_reflog_entry(&contents, &update->old_oid, &update->new_oid,
+					    update->committer_info, update->msg);
+			if (contents.len >= 65536) {
+				if (write_in_full(fd, contents.buf, contents.len) < 0)
+					goto write_error;
+				strbuf_reset(&contents);
+			}
+		}
+		if (write_in_full(fd, contents.buf, contents.len) < 0)
+			goto write_error;
+		strbuf_reset(&contents);
+		if (adjust_shared_perm(refs->base.repo, get_tempfile_path(log->file)) ||
+		    close_tempfile_gently(log->file))
+			goto write_error;
+	}
+	ret = 0;
+	goto out;
+
+write_error:
+	strbuf_addf(err, "cannot write staged reflog: %s", strerror(errno));
+out:
+	strbuf_release(&path);
+	strbuf_release(&contents);
+	return ret;
+}
+
+static int install_reflog(const char *path, void *data)
+{
+	struct staged_reflog *log = data;
+	int ret = rename(get_tempfile_path(log->file), path);
+
+	/* Some systems report ENOTDIR when the destination is a directory. */
+	if (ret && errno == ENOTDIR)
+		errno = EISDIR;
+	return ret;
+}
+
 /*
  * Prepare for carrying out update:
  * - Lock the reference referred to by update.
@@ -2929,6 +3047,17 @@ static void files_transaction_cleanup(struct files_ref_store *refs,
 	}
 
 	if (backend_data) {
+		struct hashmap_iter iter;
+		struct strmap_entry *entry;
+
+		strmap_for_each_entry(&backend_data->reflog_files, &iter, entry) {
+			struct staged_reflog *log = entry->value;
+
+			delete_tempfile(&log->file);
+			free(log->updates);
+			free(log);
+		}
+		strmap_clear(&backend_data->reflog_files, 0);
 		if (backend_data->packed_transaction &&
 		    ref_transaction_abort(backend_data->packed_transaction, &err)) {
 			error("error aborting transaction: %s", err.buf);
@@ -2970,6 +3099,7 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 
 	CALLOC_ARRAY(backend_data, 1);
 	strmap_init(&backend_data->ref_locks);
+	strmap_init(&backend_data->reflog_files);
 	transaction->backend_data = backend_data;
 
 	/*
@@ -3120,6 +3250,8 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 		}
 	}
 
+	ret = prepare_reflog_replacements(refs, transaction, err);
+
 cleanup:
 	free(head_ref);
 	string_list_clear(&refnames_to_check, 1);
@@ -3344,6 +3476,31 @@ static int files_transaction_finish(struct ref_store *ref_store,
 	backend_data = transaction->backend_data;
 	packed_transaction = backend_data->packed_transaction;
 
+	for (i = 0; i < transaction->nr; i++) {
+		struct ref_update *update = transaction->updates[i];
+		struct staged_reflog *log;
+
+		if (!(update->flags & REF_REPLACE_REFLOG))
+			continue;
+		log = strmap_get(&backend_data->reflog_files, update->refname);
+		strbuf_reset(&sb);
+		files_reflog_path(refs, &sb, update->refname);
+		if (!log->file) {
+			if (unlink(sb.buf) && errno != ENOENT && errno != EISDIR)
+				ret = -1;
+		} else if (raceproof_create_file(refs, sb.buf, install_reflog, log)) {
+			ret = -1;
+		} else {
+			delete_tempfile(&log->file);
+		}
+		if (ret) {
+			strbuf_addf(err, "cannot replace reflog '%s': %s",
+				    update->refname, strerror(errno));
+		}
+		if (ret)
+			goto cleanup;
+	}
+
 	/* Perform updates first so live commits remain referenced */
 	for (i = 0; i < transaction->nr; i++) {
 		struct ref_update *update = transaction->updates[i];
@@ -3352,8 +3509,9 @@ static int files_transaction_finish(struct ref_store *ref_store,
 		if (update->rejection_err)
 			continue;
 
-		if (update->flags & REF_NEEDS_COMMIT ||
-		    update->flags & REF_LOG_ONLY) {
+		if ((update->flags & REF_NEEDS_COMMIT ||
+		     update->flags & REF_LOG_ONLY) &&
+		    !strmap_contains(&backend_data->reflog_files, update->refname)) {
 			if (parse_and_write_reflog(refs, update, lock, err)) {
 				ret = REF_TRANSACTION_ERROR_GENERIC;
 				goto cleanup;
diff --git a/refs/refs-internal.h b/refs/refs-internal.h
index 0b41f5fa4b..19fdf39d1d 100644
--- a/refs/refs-internal.h
+++ b/refs/refs-internal.h
@@ -49,6 +49,9 @@ struct ref_transaction;
  */
 #define REF_HAVE_PEELED (1 << 15)
 
+/* Replace a reflog with the explicit log-only updates in the transaction. */
+#define REF_REPLACE_REFLOG (1 << 16)
+
 /*
  * Return the length of time to retry acquiring a loose reference lock
  * before giving up, in milliseconds:
diff --git a/refs/reftable-backend.c b/refs/reftable-backend.c
index 10db03991e..203b111f3d 100644
--- a/refs/reftable-backend.c
+++ b/refs/reftable-backend.c
@@ -1503,9 +1503,11 @@ static int write_transaction_table(struct reftable_writer *writer, void *cb_data
 		 * - `core.logAllRefUpdates` tells us to create the reflog for
 		 *   the given ref.
 		 */
-		if ((u->flags & REF_HAVE_NEW) &&
+		if ((u->flags & REF_REPLACE_REFLOG) ||
+		    ((u->flags & REF_HAVE_NEW) &&
+		    !(u->flags & REF_LOG_ONLY) &&
 		    !(u->type & REF_ISSYMREF) &&
-		    ref_update_has_null_new_value(u)) {
+		    ref_update_has_null_new_value(u))) {
 			struct reftable_log_record log = {0};
 			struct reftable_iterator it = {0};
 
@@ -1548,8 +1550,10 @@ static int write_transaction_table(struct reftable_writer *writer, void *cb_data
 
 			if (ret)
 				goto done;
-		} else if (!(u->flags & REF_SKIP_CREATE_REFLOG) &&
+		}
+		if (!(u->flags & REF_SKIP_CREATE_REFLOG) &&
 			   (u->flags & REF_HAVE_NEW) &&
+			   (!ref_update_has_null_new_value(u) || (u->flags & REF_LOG_ONLY)) &&
 			   (u->flags & REF_FORCE_CREATE_REFLOG ||
 			    should_write_log(arg->refs, u->refname))) {
 			struct reftable_log_record *log;
diff --git a/t/helper/test-ref-store.c b/t/helper/test-ref-store.c
index db58f00589..7ce10c28af 100644
--- a/t/helper/test-ref-store.c
+++ b/t/helper/test-ref-store.c
@@ -146,6 +146,45 @@ static int cmd_rename_ref(struct ref_store *refs, const char **argv)
 	return refs_rename_ref(refs, oldref, newref, logmsg);
 }
 
+static int cmd_reflog_transaction(struct ref_store *refs, const char **argv)
+{
+	const char *refname = notnull(*argv++, "refname");
+	const char *mode = notnull(*argv++, "mode");
+	struct strbuf err = STRBUF_INIT;
+	struct ref_transaction *transaction = ref_store_transaction_begin(refs, 0, &err);
+	int ret = !transaction;
+
+	if (!ret) {
+		if (!strcmp(mode, "replace")) {
+			ret = ref_transaction_replace_reflog(transaction, refname, &err);
+		} else if (!strcmp(mode, "replace-twice")) {
+			ret = ref_transaction_replace_reflog(transaction, refname, &err) ||
+				ref_transaction_replace_reflog(transaction, refname, &err);
+		} else if (strcmp(mode, "append")) {
+			die("unknown reflog transaction mode: %s", mode);
+		}
+	}
+	while (!ret && *argv) {
+		uint64_t index = strtoumax(notnull(*argv++, "index"), NULL, 10);
+		struct object_id old_oid, new_oid;
+		const char *message;
+
+		if (get_oid_hex(notnull(*argv++, "old-oid"), &old_oid) ||
+		    get_oid_hex(notnull(*argv++, "new-oid"), &new_oid))
+			die("invalid object ID");
+		message = notnull(*argv++, "message");
+		ret = ref_transaction_update_reflog(transaction, refname,
+				&new_oid, &old_oid, NULL, message, index, &err);
+	}
+	if (!ret)
+		ret = ref_transaction_commit(transaction, &err);
+	if (ret)
+		error("%s", err.buf);
+	ref_transaction_free(transaction);
+	strbuf_release(&err);
+	return ret;
+}
+
 static int each_ref(const struct reference *ref, void *cb_data UNUSED)
 {
 	printf("%s %s 0x%x\n", oid_to_hex(ref->oid), ref->name, ref->flags);
@@ -308,6 +347,7 @@ static struct command commands[] = {
 	{ "create-symref", cmd_create_symref },
 	{ "delete-refs", cmd_delete_refs },
 	{ "rename-ref", cmd_rename_ref },
+	{ "reflog-transaction", cmd_reflog_transaction },
 	{ "for-each-ref", cmd_for_each_ref },
 	{ "for-each-ref--exclude", cmd_for_each_ref__exclude },
 	{ "resolve-ref", cmd_resolve_ref },
diff --git a/t/t1425-reflog-transaction.sh b/t/t1425-reflog-transaction.sh
new file mode 100755
index 0000000000..ee5278045e
--- /dev/null
+++ b/t/t1425-reflog-transaction.sh
@@ -0,0 +1,59 @@
+#!/bin/sh
+
+test_description='explicit reflog entries in reference transactions'
+
+. ./test-lib.sh
+
+test_expect_success 'setup' '
+	test_commit A &&
+	test_commit B &&
+	A=$(git rev-parse A) &&
+	B=$(git rev-parse B)
+'
+
+test_expect_success 'log-only entry with null new OID does not delete existing history' '
+	git branch source "$A" &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/source >before &&
+	test-tool ref-store main reflog-transaction refs/heads/source append \
+		1 "$A" "$ZERO_OID" deletion &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/source >after &&
+	sed "$ d" after >history &&
+	test_cmp before history &&
+	test_grep "$A $ZERO_OID .*deletion" after &&
+	test_cmp_rev "$A" source
+'
+
+test_expect_success 'replace reflog with entries ordered by index' '
+	test-tool ref-store main reflog-transaction refs/heads/source replace \
+		2 "$A" "$B" second \
+		1 "$ZERO_OID" "$A" first &&
+	git reflog show --format=%gs source >actual &&
+	printf "%s\n" second first >expect &&
+	test_cmp expect actual &&
+	test_cmp_rev "$A" source
+'
+
+test_expect_success 'prepared hook can reject replacement without losing history' '
+	test_when_finished "rm -f .git/hooks/reference-transaction" &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/source >before &&
+	write_script .git/hooks/reference-transaction <<-\EOF &&
+		test "$1" != prepared
+	EOF
+	test_must_fail test-tool ref-store main reflog-transaction refs/heads/source replace \
+		1 "$ZERO_OID" "$B" replacement &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/source >after &&
+	test_cmp before after
+'
+
+test_expect_success 'replacement with no entries removes only the reflog' '
+	test-tool ref-store main reflog-transaction refs/heads/source replace &&
+	test_must_fail git reflog exists refs/heads/source &&
+	test_cmp_rev "$A" source
+'
+
+test_expect_success 'duplicate replacement is rejected' '
+	test_must_fail test-tool ref-store main reflog-transaction \
+		refs/heads/source replace-twice
+'
+
+test_done
-- 
2.39.3 (Apple Git-146)
[PATCH v3 3/4] refs: run copy and rename through ordinary transactions
#43
Author: Maciej Ciemborowicz
Date: Wed, 07 Oct 2026 18:05
1226 lines
54365 bytes
Copy and rename currently bypass reference transactions. A hook sees the
source deletion with files and sees neither endpoint with reftable.
Queue the source and destination as ordinary updates instead, with the
destination referring to its source update.

Read and lock the source during prepare, then replay its history through
the explicit reflog API. Keep this state per update so multiple
independent operations and ordinary updates can share a transaction. Do
not reject source changes made before locking: preparing is advisory,
while prepared sees the values read under lock and unchanged on-disk
refs and reflogs.

For files D/F and case-only renames, the source prevents locking a loose
destination. Queue the destination in packed-refs, protected by the
source lock (and an ancestor lock when needed). Suppress hooks for this
physical child transaction only. Keep source logs until finish and use
the staged replacements so a veto needs no rollback writes. During
finish, retain a unique backup of a D/F source log until its destination
log is installed, and restore it if installation fails.

Preserve the backends' distinct final reflog records. Forced reftable
copies now replace destination history instead of retaining unrelated
destination entries. Add regression tests for hooks, full histories,
HEAD, source races, mixed transactions, lock and installation errors,
restoration and cleanup, and a reproducible performance test.

Replaying history costs O(N) time and memory. In a local no-hook
benchmark with 10,000 entries, files rename takes about 17 ms versus 5
ms before, and reftable rename about 54 ms versus 44 ms. Short-history
operations remain within roughly 1 ms. This trades the files
constant-time rename for staging that does not expose partial changes to
a prepared hook.

Helped-by: Karthik Nayak <karthik.188@gmail.com>
Helped-by: Junio C Hamano <gitster@pobox.com>
Helped-by: Patrick Steinhardt <ps@pks.im>
Signed-off-by: Maciej Ciemborowicz <maciej.ciemborowicz@gmail.com>
---
 Documentation/githooks.adoc     |  10 +
 refs.c                          | 163 +++++++++++++--
 refs.h                          |  16 ++
 refs/files-backend.c            | 225 +++++++++++++++++++-
 refs/refs-internal.h            |  13 ++
 refs/reftable-backend.c         |  37 +++-
 t/helper/test-ref-store.c       |  36 ++++
 t/perf/p1424-ref-copy-rename.sh |  48 +++++
 t/t1424-ref-copy-transaction.sh | 352 ++++++++++++++++++++++++++++++++
 9 files changed, 880 insertions(+), 20 deletions(-)
 create mode 100755 t/perf/p1424-ref-copy-rename.sh
 create mode 100755 t/t1424-ref-copy-transaction.sh

diff --git a/Documentation/githooks.adoc b/Documentation/githooks.adoc
index ed045940d1..629dd3e4d1 100644
--- a/Documentation/githooks.adoc
+++ b/Documentation/githooks.adoc
@@ -518,6 +518,16 @@ distinguish these cases, you can inspect the current value of
 references are not resolved: `<ref-name>` will reflect the symbolic reference
 itself rather than the object it points to.
 
+Copying or renaming a reference is reported as one transaction. A rename
+reports the deletion of the source and the update of the destination;
+a copy reports only the destination update. Copying the reflog does not
+produce additional hook input. In the "preparing" state, the old values
+are unspecified (all zeroes), and the destination's new value is the
+source value read before locking. In subsequent states, these operations
+report the old values and the source value read under lock. Thus, a
+"preparing" hook may change the source before it is copied or renamed.
+A "prepared" hook still sees the original references and reflogs on disk.
+
 For symbolic reference updates the `<old_value>` and `<new-value>`
 fields could denote references instead of objects. A reference will be
 denoted with a 'ref:' prefix, like `ref:<ref-target>`.
diff --git a/refs.c b/refs.c
index bf219573cd..eb3e58c789 100644
--- a/refs.c
+++ b/refs.c
@@ -3158,28 +3158,165 @@ int refs_delete_refs(struct ref_store *refs, const char *logmsg,
 	return ret;
 }
 
+static int transaction_copy_ref(struct ref_transaction *transaction,
+				const char *oldref, const char *newref,
+				unsigned int source_flags, const char *logmsg,
+				struct strbuf *err)
+{
+	struct ref_update *source, *destination;
+	struct object_id oid;
+	int type;
+
+	if (transaction->state != REF_TRANSACTION_OPEN)
+		BUG("copy added to a prepared transaction");
+	if (!refs_resolve_ref_unsafe(transaction->ref_store, oldref,
+			RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE, &oid, &type)) {
+		strbuf_addf(err, _("refname %s not found"), oldref);
+		return -1;
+	}
+	if (type & REF_ISSYMREF) {
+		strbuf_addf(err, _("refname %s is a symbolic ref, copying or renaming it is not supported"), oldref);
+		return -1;
+	}
+	if (!strcmp(oldref, newref))
+		return 0;
+	if (!transaction_refname_valid(newref, &oid, REF_NO_DEREF, err))
+		return -1;
+	if (transaction->flags & (REF_TRANSACTION_FLAG_INITIAL | REF_TRANSACTION_ALLOW_FAILURE)) {
+		strbuf_addstr(err, _("copy and rename require an all-or-nothing, non-initial transaction"));
+		return -1;
+	}
+
+	/* This value describes the request to 'preparing'; locks decide the value used. */
+	source = ref_transaction_add_update(transaction, oldref,
+			REF_NO_DEREF | REF_COPY_SOURCE | source_flags,
+			(source_flags & REF_HAVE_NEW) ? null_oid(transaction->ref_store->repo->hash_algo) : NULL,
+			NULL, NULL, NULL, NULL, NULL, logmsg);
+	destination = ref_transaction_add_update(transaction, newref,
+			REF_NO_DEREF | REF_HAVE_NEW,
+			&oid, NULL, NULL, NULL, NULL, NULL, logmsg);
+	destination->copy_from = source;
+	return ref_transaction_replace_reflog(transaction, newref, err);
+}
+
+int ref_transaction_copy(struct ref_transaction *transaction,
+			 const char *oldref, const char *newref,
+			 const char *logmsg, struct strbuf *err)
+{
+	return transaction_copy_ref(transaction, oldref, newref,
+				    REF_LOG_ONLY | REF_SKIP_CREATE_REFLOG, logmsg, err);
+}
+
+int ref_transaction_rename(struct ref_transaction *transaction,
+			   const char *oldref, const char *newref,
+			   const char *logmsg, struct strbuf *err)
+{
+	return transaction_copy_ref(transaction, oldref, newref,
+				    REF_HAVE_NEW, logmsg, err);
+}
+
+int ref_update_record_copy_source(struct ref_update *update,
+				  const struct object_id *oid,
+				  struct strbuf *err)
+{
+	if ((update->type & REF_ISSYMREF) || is_null_oid(oid)) {
+		strbuf_addf(err, _("'%s' is not an existing direct reference"), update->refname);
+		return -1;
+	}
+	oidcpy(&update->old_oid, oid);
+	update->flags |= REF_HAVE_OLD;
+	return 0;
+}
+
+struct copy_reflog_data {
+	struct ref_transaction *transaction;
+	const char *refname;
+	struct strbuf *err;
+};
+
+static int copy_reflog_entry(const char *refname UNUSED,
+			     struct object_id *old_oid, struct object_id *new_oid,
+			     const char *committer, timestamp_t timestamp, int tz,
+			     const char *message, void *cb_data)
+{
+	struct copy_reflog_data *data = cb_data;
+	struct strbuf ident = STRBUF_INIT;
+	int ret;
+
+	strbuf_addf(&ident, "%s %" PRItime " %+05d", committer, timestamp, tz);
+	ret = ref_transaction_update_reflog(data->transaction, data->refname,
+			new_oid, old_oid, ident.buf, message,
+			data->transaction->max_index + 1, data->err);
+	strbuf_release(&ident);
+	return ret;
+}
+
+int ref_transaction_prepare_copy(struct ref_transaction *transaction,
+				 struct ref_update *update,
+				 struct strbuf *err)
+{
+	struct ref_update *source = update->copy_from;
+	struct copy_reflog_data data = { transaction, update->refname, err };
+	struct object *object;
+	int ret;
+
+	oidcpy(&update->new_oid, &source->old_oid);
+	object = parse_object(transaction->ref_store->repo, &update->new_oid);
+	if (!object || (is_branch(update->refname) && object->type != OBJ_COMMIT)) {
+		strbuf_addf(err, _("cannot copy object %s to '%s'"),
+			    oid_to_hex(&update->new_oid), update->refname);
+		return -1;
+	}
+	if (object->type == OBJ_TAG &&
+	    !peel_object(transaction->ref_store->repo, &update->new_oid,
+			 &update->peeled, PEEL_OBJECT_VERIFY_TAGGED_OBJECT_TYPE))
+		update->flags |= REF_HAVE_PEELED;
+
+	if (!refs_reflog_exists(transaction->ref_store, source->refname))
+		return 0;
+	ret = refs_for_each_reflog_ent(transaction->ref_store, source->refname,
+				       copy_reflog_entry, &data);
+	if (ret && !err->len)
+		strbuf_addf(err, _("cannot read reflog for '%s'"), source->refname);
+	return ret;
+}
+
 int refs_rename_ref(struct ref_store *refs, const char *oldref,
 		    const char *newref, const char *logmsg)
 {
-	char *msg;
-	int retval;
+	struct strbuf err = STRBUF_INIT;
+	struct ref_transaction *transaction = ref_store_transaction_begin(refs, 0, &err);
+	int ret = -1;
 
-	msg = normalize_reflog_message(logmsg);
-	retval = refs->be->rename_ref(refs, oldref, newref, msg);
-	free(msg);
-	return retval;
+	if (!transaction ||
+	    ref_transaction_rename(transaction, oldref, newref, logmsg, &err))
+		goto out;
+	ret = transaction->nr ? ref_transaction_commit(transaction, &err) : 0;
+out:
+	if (ret)
+		error("%s", err.buf);
+	ref_transaction_free(transaction);
+	strbuf_release(&err);
+	return ret;
 }
 
 int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
-		    const char *newref, const char *logmsg)
+			   const char *newref, const char *logmsg)
 {
-	char *msg;
-	int retval;
+	struct strbuf err = STRBUF_INIT;
+	struct ref_transaction *transaction = ref_store_transaction_begin(refs, 0, &err);
+	int ret = -1;
 
-	msg = normalize_reflog_message(logmsg);
-	retval = refs->be->copy_ref(refs, oldref, newref, msg);
-	free(msg);
-	return retval;
+	if (!transaction ||
+	    ref_transaction_copy(transaction, oldref, newref, logmsg, &err))
+		goto out;
+	ret = transaction->nr ? ref_transaction_commit(transaction, &err) : 0;
+out:
+	if (ret)
+		error("%s", err.buf);
+	ref_transaction_free(transaction);
+	strbuf_release(&err);
+	return ret;
 }
 
 const char *ref_update_original_update_refname(struct ref_update *update)
diff --git a/refs.h b/refs.h
index 7e80d0bdfb..2538c611cd 100644
--- a/refs.h
+++ b/refs.h
@@ -948,6 +948,22 @@ int ref_transaction_replace_reflog(struct ref_transaction *transaction,
 				    const char *refname,
 				    struct strbuf *err);
 
+/*
+ * Queue a copy or rename of a direct reference and its reflog. The source is
+ * read again under lock during prepare; changes made by the preparing hook
+ * are included. An existing destination is overwritten without dereferencing
+ * it. Several independent copies, renames and ordinary updates may be queued
+ * together. Each destination (and each source being renamed) must be unique.
+ * Initial transactions and transactions allowing individual failures are not
+ * supported. On failure, discard the transaction.
+ */
+int ref_transaction_copy(struct ref_transaction *transaction,
+			 const char *oldref, const char *newref,
+			 const char *logmsg, struct strbuf *err);
+int ref_transaction_rename(struct ref_transaction *transaction,
+			   const char *oldref, const char *newref,
+			   const char *logmsg, struct strbuf *err);
+
 /*
  * Add a reference creation to transaction. new_oid is the value that
  * the reference should have after the update; it must not be
diff --git a/refs/files-backend.c b/refs/files-backend.c
index 70d1ff80c4..9e22f62d3f 100644
--- a/refs/files-backend.c
+++ b/refs/files-backend.c
@@ -74,6 +74,12 @@ extern int ignore_case;
  */
 #define REF_LOG_VIA_SPLIT (1 << 14)
 
+/* A D/F or case-only rename cannot lock a loose destination beside its source. */
+#define REF_NEEDS_PACK (1 << 18)
+
+/* The source reflog was removed to make room for its rename destination. */
+#define REF_RENAMED_LOG (1 << 19)
+
 struct ref_lock {
 	char *ref_name;
 	struct lock_file lk;
@@ -788,6 +794,37 @@ static enum ref_transaction_error lock_raw_ref(struct files_ref_store *refs,
 	lock->count = 1;
 	files_ref_path(refs, &ref_file, refname);
 
+	if (update->copy_from && (update->copy_from->flags & REF_HAVE_NEW)) {
+		const char *source = update->copy_from->refname;
+		size_t source_len = strlen(source), dest_len = strlen(refname);
+		int source_is_parent = starts_with(refname, source) && refname[source_len] == '/';
+		int dest_is_parent = starts_with(source, refname) && source[dest_len] == '/';
+		int same_path = repo_ignore_case(refs->base.repo) && !strcasecmp(source, refname);
+
+		if (source_is_parent || dest_is_parent || same_path) {
+			struct string_list skip = STRING_LIST_INIT_NODUP;
+
+			string_list_insert(&skip, source);
+			ret = refs_verify_refname_available(&refs->base, refname,
+							   extras, &skip, 0, err);
+			string_list_clear(&skip, 0);
+			if (ret)
+				goto error_return;
+			/* The existing source and its lock protect a child or case-only destination. */
+			if (dest_is_parent && repo_hold_lock_file_for_update_timeout(
+					refs->base.repo, &lock->lk, ref_file.buf, LOCK_NO_DEREF,
+					get_files_ref_lock_timeout_ms(refs->base.repo)) < 0) {
+				unable_to_lock_message(ref_file.buf, errno, err);
+				ret = REF_TRANSACTION_ERROR_GENERIC;
+				goto error_return;
+			}
+			oidclr(&lock->old_oid, refs->base.repo->hash_algo);
+			update->flags |= REF_NEEDS_PACK;
+			ret = 0;
+			goto out;
+		}
+	}
+
 retry:
 	switch (safe_create_leading_directories(refs->base.repo, ref_file.buf)) {
 	case SCLD_OK:
@@ -2538,7 +2575,8 @@ static enum ref_transaction_error split_head_update(struct ref_update *update,
 
 	new_update = ref_transaction_add_update(
 			transaction, "HEAD",
-			update->flags | REF_LOG_ONLY | REF_NO_DEREF | REF_LOG_VIA_SPLIT,
+			(update->flags & ~REF_COPY_SOURCE) |
+			REF_LOG_ONLY | REF_NO_DEREF | REF_LOG_VIA_SPLIT,
 			&update->new_oid, &update->old_oid, &update->peeled,
 			NULL, NULL, update->committer_info, update->msg);
 	new_update->parent_update = update;
@@ -2677,6 +2715,7 @@ static enum ref_transaction_error check_old_oid(struct ref_update *update,
 
 struct staged_reflog {
 	struct tempfile *file;
+	struct tempfile *source_log;
 	struct ref_update **updates;
 	size_t nr, alloc;
 };
@@ -2789,6 +2828,155 @@ static int install_reflog(const char *path, void *data)
 	return ret;
 }
 
+static int move_reflog(const char *path, void *data)
+{
+	struct tempfile *tempfile = data;
+	int ret = rename(get_tempfile_path(tempfile), path);
+
+	if (ret && errno == ENOTDIR)
+		errno = EISDIR;
+	return ret;
+}
+
+static int stage_source_reflog(struct files_ref_store *refs,
+			       struct ref_update *update,
+			       struct staged_reflog *log,
+			       struct strbuf *err)
+{
+	struct strbuf source = STRBUF_INIT;
+	struct strbuf path = STRBUF_INIT;
+	int ret = -1;
+
+	files_reflog_path(refs, &source, update->copy_from->refname);
+	if (!refs_reflog_exists(&refs->base, update->copy_from->refname)) {
+		ret = 0;
+		goto out;
+	}
+	files_reflog_path(refs, &path, "refs/.tmp-reflog-source-XXXXXX");
+	log->source_log = mks_tempfile_m(path.buf, 0666);
+	if (!log->source_log || close_tempfile_gently(log->source_log) ||
+	    rename(source.buf, get_tempfile_path(log->source_log))) {
+		strbuf_addf(err, "cannot stage source reflog '%s': %s",
+			    update->copy_from->refname, strerror(errno));
+		goto out;
+	}
+	try_remove_empty_parents(refs, update->copy_from->refname,
+				 REMOVE_EMPTY_PARENTS_REFLOG);
+	update->copy_from->flags |= REF_RENAMED_LOG;
+	ret = 0;
+
+out:
+	if (ret)
+		delete_tempfile(&log->source_log);
+	strbuf_release(&source);
+	strbuf_release(&path);
+	return ret;
+}
+
+static int restore_source_reflog(struct files_ref_store *refs,
+				 struct ref_update *update,
+				 struct staged_reflog *log,
+				 struct strbuf *err)
+{
+	struct strbuf source = STRBUF_INIT;
+	int ret;
+
+	if (!log->source_log)
+		return 0;
+	files_reflog_path(refs, &source, update->copy_from->refname);
+	ret = raceproof_create_file(refs, source.buf, move_reflog,
+				    log->source_log);
+	if (ret) {
+		struct strbuf recovery = STRBUF_INIT;
+
+		strbuf_addf(err, "; cannot restore source reflog '%s': %s",
+			    update->copy_from->refname, strerror(errno));
+		strbuf_addf(&recovery, "%s.recovery",
+			    get_tempfile_path(log->source_log));
+		if (rename_tempfile(&log->source_log, recovery.buf))
+			strbuf_addf(err, "; cannot preserve its backup: %s",
+				    strerror(errno));
+		else
+			strbuf_addf(err, "; backup saved as '%s'", recovery.buf);
+		strbuf_release(&recovery);
+	} else {
+		delete_tempfile(&log->source_log);
+	}
+	strbuf_release(&source);
+	return ret;
+}
+
+static int check_reflog_symlink(struct files_ref_store *refs,
+				const char *refname, struct strbuf *err)
+{
+	struct strbuf path = STRBUF_INIT;
+	struct stat st;
+	int ret = 0;
+
+	files_reflog_path(refs, &path, refname);
+	if (!lstat(path.buf, &st)) {
+		if (S_ISLNK(st.st_mode)) {
+			strbuf_addf(err, "reflog for %s is a symlink", refname);
+			ret = -1;
+		}
+	} else if (errno != ENOENT && errno != ENOTDIR) {
+		strbuf_addf(err, "cannot stat reflog for %s: %s", refname, strerror(errno));
+		ret = -1;
+	}
+	strbuf_release(&path);
+	return ret;
+}
+
+static struct ref_update *find_update_with_flag(struct ref_transaction *transaction,
+						const char *refname,
+						unsigned int flag)
+{
+	size_t i;
+
+	for (i = 0; i < transaction->nr; i++) {
+		struct ref_update *update = transaction->updates[i];
+
+		if ((update->flags & flag) && !strcmp(update->refname, refname))
+			return update;
+	}
+	return NULL;
+}
+
+static int prepare_copy_reflog(struct files_ref_store *refs,
+			       struct ref_transaction *transaction,
+			       struct ref_update *update, struct strbuf *err)
+{
+	enum log_refs_config config = files_ref_store_write_options(refs)->log_all_ref_updates;
+	int source_has_log;
+	int write_log;
+
+	if (check_reflog_symlink(refs, update->copy_from->refname, err) ||
+	    check_reflog_symlink(refs, update->refname, err))
+		return -1;
+	source_has_log = refs_reflog_exists(&refs->base, update->copy_from->refname);
+	/* A copy without source history only appends to an existing destination log. */
+	if (!source_has_log && !(update->copy_from->flags & REF_HAVE_NEW)) {
+		struct ref_update *replacement = find_update_with_flag(
+			transaction, update->refname, REF_REPLACE_REFLOG);
+
+		if (!replacement)
+			BUG("copy destination without a reflog replacement");
+		replacement->flags &= ~REF_REPLACE_REFLOG;
+	}
+	if (config == LOG_REFS_UNSET)
+		config = is_bare_repository(refs->base.repo) ? LOG_REFS_NONE : LOG_REFS_NORMAL;
+	write_log = source_has_log || should_autocreate_reflog(config, update->refname) ||
+		(!(update->copy_from->flags & REF_HAVE_NEW) &&
+		 refs_reflog_exists(&refs->base, update->refname));
+	if (ref_transaction_prepare_copy(transaction, update, err))
+		return -1;
+	if (!write_log)
+		return 0;
+	return ref_transaction_update_reflog(transaction, update->refname,
+			&update->new_oid, &update->new_oid, NULL, update->msg,
+			transaction->max_index + 1, err);
+}
+
 /*
  * Prepare for carrying out update:
  * - Lock the reference referred to by update.
@@ -2819,6 +3007,8 @@ static enum ref_transaction_error lock_ref_for_update(struct files_ref_store *re
 	files_assert_main_repository(refs, "lock_ref_for_update");
 
 	backend_data = transaction->backend_data;
+	if (update->copy_from && prepare_copy_reflog(refs, transaction, update, err))
+		return REF_TRANSACTION_ERROR_GENERIC;
 
 	if ((update->flags & REF_HAVE_NEW) && ref_update_has_null_new_value(update))
 		update->flags |= REF_DELETING;
@@ -2828,6 +3018,8 @@ static enum ref_transaction_error lock_ref_for_update(struct files_ref_store *re
 		if (ret)
 			goto out;
 	}
+	if (update->copy_from)
+		update->flags |= REF_SKIP_CREATE_REFLOG;
 
 	lock = strmap_get(&backend_data->ref_locks, update->refname);
 	if (lock) {
@@ -2849,6 +3041,17 @@ static enum ref_transaction_error lock_ref_for_update(struct files_ref_store *re
 	}
 
 	update->backend_data = lock;
+	if (update->copy_from) {
+		oidcpy(&update->old_oid, &lock->old_oid);
+		if (update->type & REF_ISSYMREF)
+			update->old_target = xstrdup(referent.buf);
+		update->flags |= REF_HAVE_OLD;
+	}
+	if ((update->flags & REF_COPY_SOURCE) &&
+	    ref_update_record_copy_source(update, &lock->old_oid, err)) {
+		ret = REF_TRANSACTION_ERROR_GENERIC;
+		goto out;
+	}
 
 	if (update->flags & REF_LOG_VIA_SPLIT) {
 		struct ref_lock *parent_lock;
@@ -2974,7 +3177,7 @@ static enum ref_transaction_error lock_ref_for_update(struct files_ref_store *re
 		update->flags |= REF_NEEDS_COMMIT;
 	} else if ((update->flags & REF_HAVE_NEW) &&
 		   !(update->flags & REF_DELETING) &&
-		   !(update->flags & REF_LOG_ONLY)) {
+		   !(update->flags & (REF_LOG_ONLY | REF_NEEDS_PACK))) {
 		if (!(update->type & REF_ISSYMREF) &&
 		    oideq(&lock->old_oid, &update->new_oid)) {
 			/*
@@ -3003,7 +3206,7 @@ static enum ref_transaction_error lock_ref_for_update(struct files_ref_store *re
 			}
 		}
 	}
-	if (!(update->flags & REF_NEEDS_COMMIT)) {
+	if (!(update->flags & (REF_NEEDS_COMMIT | REF_NEEDS_PACK))) {
 		/*
 		 * We didn't call write_ref_to_lockfile(), so
 		 * the lockfile is still open. Close it to
@@ -3054,6 +3257,7 @@ static void files_transaction_cleanup(struct files_ref_store *refs,
 			struct staged_reflog *log = entry->value;
 
 			delete_tempfile(&log->file);
+			delete_tempfile(&log->source_log);
 			free(log->updates);
 			free(log);
 		}
@@ -3162,7 +3366,7 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 			goto cleanup;
 		}
 
-		if (update->flags & REF_DELETING &&
+		if (update->flags & (REF_DELETING | REF_NEEDS_PACK) &&
 		    !(update->flags & REF_LOG_ONLY) &&
 		    !(update->flags & REF_IS_PRUNING)) {
 			/*
@@ -3187,6 +3391,8 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 					REF_HAVE_NEW | REF_NO_DEREF,
 					&update->new_oid, NULL, NULL,
 					NULL, NULL, NULL, NULL);
+			if (update->copy_from || (update->flags & REF_COPY_SOURCE))
+				packed_transaction->flags |= REF_TRANSACTION_FLAG_INTERNAL;
 		}
 	}
 
@@ -3478,11 +3684,18 @@ static int files_transaction_finish(struct ref_store *ref_store,
 
 	for (i = 0; i < transaction->nr; i++) {
 		struct ref_update *update = transaction->updates[i];
+		struct ref_update *operation;
 		struct staged_reflog *log;
 
 		if (!(update->flags & REF_REPLACE_REFLOG))
 			continue;
 		log = strmap_get(&backend_data->reflog_files, update->refname);
+		operation = find_update_with_flag(transaction, update->refname,
+						  REF_NEEDS_PACK);
+		if (operation && stage_source_reflog(refs, operation, log, err)) {
+			ret = -1;
+			goto cleanup;
+		}
 		strbuf_reset(&sb);
 		files_reflog_path(refs, &sb, update->refname);
 		if (!log->file) {
@@ -3496,6 +3709,8 @@ static int files_transaction_finish(struct ref_store *ref_store,
 		if (ret) {
 			strbuf_addf(err, "cannot replace reflog '%s': %s",
 				    update->refname, strerror(errno));
+			if (operation)
+				restore_source_reflog(refs, operation, log, err);
 		}
 		if (ret)
 			goto cleanup;
@@ -3560,7 +3775,7 @@ static int files_transaction_finish(struct ref_store *ref_store,
 
 		if (update->flags & REF_DELETING &&
 		    !(update->flags & REF_LOG_ONLY) &&
-		    !(update->flags & REF_IS_PRUNING)) {
+		    !(update->flags & (REF_IS_PRUNING | REF_RENAMED_LOG))) {
 			strbuf_reset(&sb);
 			files_reflog_path(refs, &sb, update->refname);
 			if (!unlink_or_warn(sb.buf))
diff --git a/refs/refs-internal.h b/refs/refs-internal.h
index 19fdf39d1d..2746ce5b49 100644
--- a/refs/refs-internal.h
+++ b/refs/refs-internal.h
@@ -52,6 +52,9 @@ struct ref_transaction;
 /* Replace a reflog with the explicit log-only updates in the transaction. */
 #define REF_REPLACE_REFLOG (1 << 16)
 
+/* A source whose value and reflog are consumed by a later update. */
+#define REF_COPY_SOURCE (1 << 17)
+
 /*
  * Return the length of time to retry acquiring a loose reference lock
  * before giving up, in milliseconds:
@@ -161,6 +164,9 @@ struct ref_update {
 	 */
 	struct ref_update *parent_update;
 
+	/* The source is queued first, so backends lock it before the destination. */
+	struct ref_update *copy_from;
+
 	const char refname[FLEX_ARRAY];
 };
 
@@ -193,6 +199,13 @@ struct ref_update *ref_transaction_add_update(
 		const char *committer_info,
 		const char *msg);
 
+int ref_update_record_copy_source(struct ref_update *update,
+				  const struct object_id *oid,
+				  struct strbuf *err);
+int ref_transaction_prepare_copy(struct ref_transaction *transaction,
+				 struct ref_update *update,
+				 struct strbuf *err);
+
 /*
  * Transaction states.
  *
diff --git a/refs/reftable-backend.c b/refs/reftable-backend.c
index 203b111f3d..72c1596c11 100644
--- a/refs/reftable-backend.c
+++ b/refs/reftable-backend.c
@@ -1076,6 +1076,22 @@ static enum ref_transaction_error prepare_single_update(struct reftable_ref_stor
 	struct object_id current_oid = {0};
 	const char *rewritten_ref;
 
+	if (u->copy_from) {
+		const struct object_id *zero = null_oid(refs->base.repo->hash_algo);
+
+		if (ref_transaction_prepare_copy(transaction, u, err))
+			return REF_TRANSACTION_ERROR_GENERIC;
+		if ((u->copy_from->flags & REF_HAVE_NEW) &&
+		    ref_transaction_update_reflog(transaction, u->refname,
+				zero, &u->new_oid, NULL, u->msg,
+				transaction->max_index + 1, err))
+			return REF_TRANSACTION_ERROR_GENERIC;
+		if (ref_transaction_update_reflog(transaction, u->refname,
+				&u->new_oid, zero, NULL, u->msg,
+				transaction->max_index + 1, err))
+			return REF_TRANSACTION_ERROR_GENERIC;
+	}
+
 	/*
 	 * There is no need to reload the respective backends here as
 	 * we have already reloaded them when preparing the transaction
@@ -1126,15 +1142,27 @@ static enum ref_transaction_error prepare_single_update(struct reftable_ref_stor
 
 		ref_transaction_add_update(
 			transaction, "HEAD",
-			u->flags | REF_LOG_ONLY | REF_NO_DEREF,
+			(u->flags & ~REF_COPY_SOURCE) |
+			REF_LOG_ONLY | REF_NO_DEREF,
 			&u->new_oid, &u->old_oid, &u->peeled, NULL, NULL,
 			NULL, u->msg);
 	}
+	if (u->copy_from)
+		u->flags |= REF_SKIP_CREATE_REFLOG;
 
 	ret = reftable_backend_read_ref(be, rewritten_ref,
 					&current_oid, referent, &u->type);
 	if (ret < 0)
 		return REF_TRANSACTION_ERROR_GENERIC;
+	if (u->copy_from) {
+		oidcpy(&u->old_oid, &current_oid);
+		if (u->type & REF_ISSYMREF)
+			u->old_target = xstrdup(referent->buf);
+		u->flags |= REF_HAVE_OLD;
+	}
+	if ((u->flags & REF_COPY_SOURCE) &&
+	    ref_update_record_copy_source(u, &current_oid, err))
+		return REF_TRANSACTION_ERROR_GENERIC;
 	if (ret > 0 && !ref_update_expects_existing_old_ref(u)) {
 		struct string_list_item *item;
 		/*
@@ -1319,6 +1347,7 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 		reftable_be_downcast(ref_store, REF_STORE_WRITE|REF_STORE_MAIN, "ref_transaction_prepare");
 	struct strbuf referent = STRBUF_INIT, head_referent = STRBUF_INIT;
 	struct string_list refnames_to_check = STRING_LIST_INIT_NODUP;
+	struct string_list renamed_sources = STRING_LIST_INIT_NODUP;
 	struct reftable_transaction_data *tx_data = NULL;
 	struct reftable_backend *be;
 	struct object_id head_oid;
@@ -1338,6 +1367,9 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 	 * that will be modified during the transaction.
 	 */
 	for (i = 0; i < transaction->nr; i++) {
+		struct ref_update *update = transaction->updates[i];
+		if (update->copy_from && (update->copy_from->flags & REF_HAVE_NEW))
+			string_list_insert(&renamed_sources, update->copy_from->refname);
 		ret = prepare_transaction_update(NULL, refs, tx_data,
 						 transaction->updates[i], err);
 		if (ret)
@@ -1390,7 +1422,7 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 	}
 
 	ret = refs_verify_refnames_available(ref_store, &refnames_to_check,
-					     &transaction->refnames, NULL,
+					     &transaction->refnames, &renamed_sources,
 					     transaction,
 					     transaction->flags & REF_TRANSACTION_FLAG_INITIAL,
 					     err);
@@ -1411,6 +1443,7 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 	strbuf_release(&referent);
 	strbuf_release(&head_referent);
 	string_list_clear(&refnames_to_check, 1);
+	string_list_clear(&renamed_sources, 0);
 
 	return ret;
 }
diff --git a/t/helper/test-ref-store.c b/t/helper/test-ref-store.c
index 7ce10c28af..ec7728334c 100644
--- a/t/helper/test-ref-store.c
+++ b/t/helper/test-ref-store.c
@@ -185,6 +185,41 @@ static int cmd_reflog_transaction(struct ref_store *refs, const char **argv)
 	return ret;
 }
 
+static int cmd_copy_transaction(struct ref_store *refs, const char **argv)
+{
+	struct strbuf err = STRBUF_INIT;
+	struct ref_transaction *transaction = ref_store_transaction_begin(refs, 0, &err);
+	int ret = !transaction;
+
+	while (!ret && *argv) {
+		const char *operation = *argv++;
+		const char *source = notnull(*argv++, "source");
+		const char *destination = notnull(*argv++, "destination");
+
+		if (!strcmp(operation, "rename"))
+			ret = ref_transaction_rename(transaction, source, destination, "rename", &err);
+		else if (!strcmp(operation, "copy"))
+			ret = ref_transaction_copy(transaction, source, destination, "copy", &err);
+		else if (!strcmp(operation, "update")) {
+			struct object_id oid;
+
+			if (get_oid_hex(destination, &oid))
+				die("invalid object ID: %s", destination);
+			ret = ref_transaction_update(transaction, source, &oid,
+						     NULL, NULL, NULL, 0, "update", &err);
+		} else {
+			die("unknown operation: %s", operation);
+		}
+	}
+	if (!ret)
+		ret = ref_transaction_commit(transaction, &err);
+	if (ret)
+		error("%s", err.buf);
+	ref_transaction_free(transaction);
+	strbuf_release(&err);
+	return ret;
+}
+
 static int each_ref(const struct reference *ref, void *cb_data UNUSED)
 {
 	printf("%s %s 0x%x\n", oid_to_hex(ref->oid), ref->name, ref->flags);
@@ -348,6 +383,7 @@ static struct command commands[] = {
 	{ "delete-refs", cmd_delete_refs },
 	{ "rename-ref", cmd_rename_ref },
 	{ "reflog-transaction", cmd_reflog_transaction },
+	{ "copy-transaction", cmd_copy_transaction },
 	{ "for-each-ref", cmd_for_each_ref },
 	{ "for-each-ref--exclude", cmd_for_each_ref__exclude },
 	{ "resolve-ref", cmd_resolve_ref },
diff --git a/t/perf/p1424-ref-copy-rename.sh b/t/perf/p1424-ref-copy-rename.sh
new file mode 100755
index 0000000000..a901129b00
--- /dev/null
+++ b/t/perf/p1424-ref-copy-rename.sh
@@ -0,0 +1,48 @@
+#!/bin/sh
+
+test_description='Copy and rename references with short and long reflogs'
+
+. ./perf-lib.sh
+
+test_perf_fresh_repo
+
+for entries in 10 10000
+do
+	export entries
+	test_expect_success "setup $entries reflog entries" '
+		git init --ref-format=files "repo-$entries" &&
+		(
+			cd "repo-$entries" &&
+			test_commit A &&
+			git branch source &&
+			oid=$(git rev-parse HEAD) &&
+			awk -v oid="$oid" -v count="$entries" '\''
+				BEGIN {
+					for (i = 0; i < count; i++)
+						printf "%s %s A <a@example.com> %d +0000\tentry %d\n", oid, oid, 1700000000 + i, i
+				}
+			'\'' >.git/logs/refs/heads/source &&
+			if test "$GIT_TEST_DEFAULT_REF_FORMAT" = reftable
+			then
+				git refs migrate --ref-format=reftable
+			fi
+		)
+	'
+
+	test_perf "copy $entries reflog entries (10 operations)" '
+		for i in $(test_seq 10)
+		do
+			git -C "repo-$entries" branch -C source destination || return 1
+		done
+	'
+
+	test_perf "rename $entries reflog entries (10 operations)" '
+		for i in $(test_seq 5)
+		do
+			git -C "repo-$entries" branch -m source renamed &&
+			git -C "repo-$entries" branch -m renamed source || return 1
+		done
+	'
+done
+
+test_done
diff --git a/t/t1424-ref-copy-transaction.sh b/t/t1424-ref-copy-transaction.sh
new file mode 100755
index 0000000000..4c7592795f
--- /dev/null
+++ b/t/t1424-ref-copy-transaction.sh
@@ -0,0 +1,352 @@
+#!/bin/sh
+
+test_description='reference transactions for copy and rename'
+
+GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main
+export GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME
+
+. ./test-lib.sh
+
+snapshot () {
+	git for-each-ref --format="%(refname) %(objectname) %(symref)" >"$1.refs" &&
+	for ref in HEAD refs/heads/source refs/heads/destination
+	do
+		if git reflog exists "$ref"
+		then
+			test-tool ref-store main for-each-reflog-ent "$ref"
+		else
+			echo missing
+		fi >"$1.$(basename "$ref").log" || return 1
+	done
+}
+
+compare_snapshot () {
+	for suffix in refs HEAD.log source.log destination.log
+	do
+		test_cmp "$1.$suffix" "$2.$suffix" || return 1
+	done
+}
+
+test_expect_success 'setup' '
+	test_commit A &&
+	test_commit B &&
+	A=$(git rev-parse A) &&
+	B=$(git rev-parse B)
+'
+
+for operation in rename copy
+do
+	test_expect_success "$operation reports one logical transaction" '
+		test_when_finished "git config --unset core.hooksPath" &&
+		git branch -f source "$A" &&
+		git branch -f destination "$B" &&
+		mkdir -p hooks &&
+		write_script hooks/reference-transaction <<-\EOF &&
+			echo "$1" >>actual &&
+			cat >>actual
+		EOF
+		git config core.hooksPath hooks &&
+		>actual &&
+		test-tool ref-store main copy-transaction "$operation" refs/heads/source refs/heads/destination &&
+		{
+			echo preparing &&
+			if test "$operation" = rename
+			then
+				echo "$ZERO_OID $ZERO_OID refs/heads/source"
+			fi &&
+			echo "$ZERO_OID $A refs/heads/destination" &&
+			for state in prepared committed
+			do
+				echo "$state" &&
+				if test "$operation" = rename
+				then
+					echo "$A $ZERO_OID refs/heads/source"
+				fi &&
+				echo "$B $A refs/heads/destination" || return 1
+			done
+		} >expect &&
+		test_cmp expect actual
+	'
+
+	for state in preparing prepared
+	do
+		test_expect_success "$operation rejected at $state leaves refs and full reflogs unchanged" '
+			test_when_finished "git config --unset core.hooksPath" &&
+			git branch -f source "$A" &&
+			git branch -f destination "$B" &&
+			git symbolic-ref HEAD refs/heads/source &&
+			test_when_finished "git -c core.hooksPath=/dev/null symbolic-ref HEAD refs/heads/main" &&
+			snapshot before &&
+			write_script hooks/reference-transaction <<-EOF &&
+				test "\$1" != "$state"
+			EOF
+			git config core.hooksPath hooks &&
+			test_must_fail test-tool ref-store main copy-transaction "$operation" refs/heads/source refs/heads/destination &&
+			snapshot after &&
+			compare_snapshot before after
+		'
+	done
+done
+
+test_expect_success 'prepared hook sees old refs and cannot modify the source' '
+	test_when_finished "git config --unset core.hooksPath" &&
+	git branch -f source "$A" &&
+	git branch -f destination "$B" &&
+	write_script hooks/reference-transaction <<-EOF &&
+		test "\$1" = prepared || exit 0
+		git rev-parse refs/heads/source >source-seen &&
+		git rev-parse refs/heads/destination >destination-seen &&
+		if git -c core.hooksPath=/dev/null -c core.filesRefLockTimeout=0 \
+			update-ref refs/heads/source $B
+		then
+			exit 1
+		fi
+	EOF
+	git config core.hooksPath hooks &&
+	git branch -M source destination &&
+	echo "$A" >expect &&
+	test_cmp expect source-seen &&
+	echo "$B" >expect &&
+	test_cmp expect destination-seen &&
+	test_cmp_rev "$A" destination
+'
+
+test_expect_success 'preparing may update source and its reflog' '
+	test_when_finished "git config --unset core.hooksPath" &&
+	git branch source "$A" &&
+	write_script hooks/reference-transaction <<-EOF &&
+		test "\$1" = preparing || exit 0
+		git -c core.hooksPath=/dev/null update-ref -m concurrent refs/heads/source $B
+	EOF
+	git config core.hooksPath hooks &&
+	git branch -M source destination &&
+	test_cmp_rev "$B" destination &&
+	git reflog show --format=%gs destination >actual &&
+	test_grep concurrent actual
+'
+
+test_expect_success 'rename without a source reflog can be rejected without losing destination history' '
+	test_when_finished "git config --unset core.hooksPath" &&
+	git -c core.logAllRefUpdates=false branch source "$A" &&
+	test_must_fail git reflog exists refs/heads/source &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/destination >before &&
+	write_script hooks/reference-transaction <<-\EOF &&
+		test "$1" != prepared
+	EOF
+	git config core.hooksPath hooks &&
+	test_must_fail git branch -M source destination &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/destination >after &&
+	test_cmp before after
+'
+
+for names in "parent parent/child" "child/branch child"
+do
+	set -- $names
+	from=$1 to=$2
+	test_expect_success "D/F rename $from to $to can be aborted and committed" '
+		test_when_finished "git config --unset core.hooksPath" &&
+		git branch "$from" "$A" &&
+		test-tool ref-store main for-each-reflog-ent "refs/heads/$from" >before &&
+		write_script hooks/reference-transaction <<-EOF &&
+			test "\$1" = prepared || exit 0
+			git rev-parse refs/heads/$from >seen
+			exit 1
+		EOF
+		git config core.hooksPath hooks &&
+		test_must_fail git branch -m "$from" "$to" &&
+		echo "$A" >expect &&
+		test_cmp expect seen &&
+		test_cmp_rev "$A" "$from" &&
+		test-tool ref-store main for-each-reflog-ent "refs/heads/$from" >after &&
+		test_cmp before after &&
+		git -c core.hooksPath=/dev/null branch -m "$from" "$to" &&
+		test_cmp_rev "$A" "$to"
+	'
+done
+
+test_expect_success REFFILES,POSIXPERM 'D/F reflog installation failure restores source history' '
+	test_when_finished "chmod u+w .git/logs/refs/heads" &&
+	test_when_finished "git config --unset core.hooksPath" &&
+	git branch rollback/branch "$A" &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/rollback/branch >before &&
+	write_script hooks/reference-transaction <<-\EOF &&
+		test "$1" = prepared || exit 0
+		chmod a-w .git/logs/refs/heads
+	EOF
+	git config core.hooksPath hooks &&
+	test_must_fail git branch -m rollback/branch rollback &&
+	chmod u+w .git/logs/refs/heads &&
+	test_cmp_rev "$A" rollback/branch &&
+	test_must_fail git show-ref --verify refs/heads/rollback &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/rollback/branch >after &&
+	test_cmp before after
+'
+
+test_expect_success 'multiple renames, a copy and an ordinary update compose' '
+	git branch first "$A" &&
+	git branch second "$B" &&
+	git branch third "$A" &&
+	test-tool ref-store main copy-transaction \
+		rename refs/heads/first refs/heads/first-new \
+		rename refs/heads/second refs/heads/second-new \
+		copy refs/heads/third refs/heads/third-new \
+		update refs/heads/fourth "$B" &&
+	test_must_fail git show-ref --verify refs/heads/first &&
+	test_must_fail git show-ref --verify refs/heads/second &&
+	test_cmp_rev "$A" first-new &&
+	test_cmp_rev "$B" second-new &&
+	test_cmp_rev "$A" third-new &&
+	test_cmp_rev "$A" third &&
+	test_cmp_rev "$B" fourth
+'
+
+test_expect_success 'copy preserves complete source history and replaces destination history' '
+	git branch history-source "$A" &&
+	git update-ref -m history-step refs/heads/history-source "$B" &&
+	git branch history-destination "$B" &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/history-source >before &&
+	git branch -C history-source history-destination &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/history-source >after &&
+	test_cmp before after &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/history-destination >copied &&
+	sed "$ d" copied >history &&
+	test_cmp before history &&
+	test_grep "Branch: copied refs/heads/history-source to refs/heads/history-destination" copied
+'
+
+test_expect_success 'packed rename reports no internal transactions' '
+	test_when_finished "git config --unset core.hooksPath" &&
+	git branch packed-source "$A" &&
+	git pack-refs --all &&
+	write_script hooks/reference-transaction <<-\EOF &&
+		echo "$1" >>states
+		cat >/dev/null
+	EOF
+	git config core.hooksPath hooks &&
+	git branch -m packed-source packed-destination &&
+	printf "%s\n" preparing prepared committed >expect &&
+	test_cmp expect states
+'
+
+test_expect_success REFFILES 'unrelated forced copies use independent reflog staging files' '
+	test_when_finished "git config --unset core.hooksPath" &&
+	git branch nested-a "$A" &&
+	git branch nested-b "$B" &&
+	git branch outer-a "$A" &&
+	git branch outer-b "$B" &&
+	write_script hooks/reference-transaction <<-\EOF &&
+		test "$1" = prepared || exit 0
+		git -c core.hooksPath=/dev/null branch -C nested-a nested-b
+	EOF
+	git config core.hooksPath hooks &&
+	git branch -C outer-a outer-b &&
+	test_cmp_rev "$A" outer-b &&
+	test_cmp_rev "$A" nested-b
+'
+
+test_expect_success REFFILES 'rename with reflogs disabled does not create a reflog' '
+	git -c core.logAllRefUpdates=false branch no-log "$A" &&
+	git -c core.logAllRefUpdates=false branch -m no-log still-no-log &&
+	test_must_fail git reflog exists refs/heads/still-no-log
+'
+
+test_expect_success REFFILES 'copy without source history retains existing destination history' '
+	git -c core.logAllRefUpdates=false branch no-copy-log "$A" &&
+	git branch existing-copy-log "$B" &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/existing-copy-log >before &&
+	git branch -C no-copy-log existing-copy-log &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/existing-copy-log >after &&
+	sed "$ d" after >history &&
+	test_cmp before history
+'
+
+test_expect_success REFFILES,CASE_INSENSITIVE_FS 'case-only rename retains history and supports abort' '
+	test_when_finished "git config --unset core.hooksPath" &&
+	git branch case-source "$A" &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/case-source >before &&
+	write_script hooks/reference-transaction <<-\EOF &&
+		test "$1" != prepared
+	EOF
+	git config core.hooksPath hooks &&
+	test_must_fail git branch -M case-source CASE-SOURCE &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/case-source >after &&
+	test_cmp before after &&
+	git -c core.hooksPath=/dev/null branch -M case-source CASE-SOURCE &&
+	git for-each-ref --format="%(refname)" refs/heads/CASE-SOURCE >actual &&
+	echo refs/heads/CASE-SOURCE >expect &&
+	test_cmp expect actual
+'
+
+test_expect_success REFFILES,SYMLINKS 'symlink source reflog is rejected without changing refs' '
+	git branch symlink-source "$A" &&
+	mv .git/logs/refs/heads/symlink-source saved-log &&
+	ln -s "$PWD/saved-log" .git/logs/refs/heads/symlink-source &&
+	test_must_fail git branch -m symlink-source symlink-destination &&
+	test_cmp_rev "$A" symlink-source &&
+	test_must_fail git show-ref --verify refs/heads/symlink-destination
+'
+
+for operation in copy rename
+do
+	test_expect_success "$operation over HEAD referent preserves HEAD history" '
+		git branch -f head-source "$A" &&
+		git update-ref refs/heads/main "$B" &&
+		test-tool ref-store main for-each-reflog-ent HEAD >before &&
+		test-tool ref-store main copy-transaction "$operation" refs/heads/head-source refs/heads/main &&
+		test-tool ref-store main for-each-reflog-ent HEAD >after &&
+		sed "$ d" after >history &&
+		test_cmp before history &&
+		test_cmp_rev "$A" HEAD
+	'
+done
+
+test_expect_success 'preparing may delete source but cannot cause a partial rename' '
+	test_when_finished "git config --unset core.hooksPath" &&
+	git branch race-source "$A" &&
+	write_script hooks/reference-transaction <<-\EOF &&
+		test "$1" = preparing || exit 0
+		git -c core.hooksPath=/dev/null update-ref -d refs/heads/race-source
+	EOF
+	git config core.hooksPath hooks &&
+	test_must_fail git branch -m race-source race-destination &&
+	test_must_fail git show-ref --verify refs/heads/race-source &&
+	test_must_fail git show-ref --verify refs/heads/race-destination
+'
+
+test_expect_success 'copy cannot replace a D/F-conflicting source' '
+	git branch conflict-source "$A" &&
+	test_must_fail git branch -c conflict-source conflict-source/child &&
+	test_cmp_rev "$A" conflict-source &&
+	test_must_fail git show-ref --verify refs/heads/conflict-source/child
+'
+
+test_expect_success REFFILES,POSIXPERM 'unreadable source reflog leaves refs and history unchanged' '
+	git branch unreadable "$A" &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/unreadable >before &&
+	test_when_finished "chmod u+r .git/logs/refs/heads/unreadable" &&
+	chmod a-r .git/logs/refs/heads/unreadable &&
+	test_must_fail git branch -m unreadable readable &&
+	chmod u+r .git/logs/refs/heads/unreadable &&
+	test_cmp_rev "$A" unreadable &&
+	test_must_fail git show-ref --verify refs/heads/readable &&
+	test-tool ref-store main for-each-reflog-ent refs/heads/unreadable >after &&
+	test_cmp before after
+'
+
+test_expect_success REFFILES 'destination lock failure preserves source and destination history' '
+	git branch -f source "$A" &&
+	git branch -f destination "$B" &&
+	snapshot before &&
+	test_when_finished "rm -f .git/refs/heads/destination.lock" &&
+	>.git/refs/heads/destination.lock &&
+	test_must_fail git -c core.filesRefLockTimeout=0 branch -M source destination &&
+	snapshot after &&
+	compare_snapshot before after
+'
+
+test_expect_success REFFILES 'staged reflog files are cleaned up after success and abort' '
+	find .git/logs -name ".tmp-reflog-*" >actual &&
+	test_must_be_empty actual
+'
+
+test_done
-- 
2.39.3 (Apple Git-146)
[PATCH v3 4/4] refs: remove backend-specific copy and rename callbacks
#41
Author: Maciej Ciemborowicz
Date: Wed, 07 Oct 2026 18:05
764 lines
32621 bytes
Copy and rename now use the transaction API for refs and reflogs. Remove
the unused callbacks, backend implementations, and their private
helpers. The files backend no longer needs a shared temporary reflog
name or rollback writes that reconstruct previously visible refs and
logs.

Signed-off-by: Maciej Ciemborowicz <maciej.ciemborowicz@gmail.com>
---
 refs/debug.c            |  24 ---
 refs/files-backend.c    | 334 ----------------------------------------
 refs/packed-backend.c   |   2 -
 refs/refs-internal.h    |   9 --
 refs/reftable-backend.c | 287 ----------------------------------
 5 files changed, 656 deletions(-)

diff --git a/refs/debug.c b/refs/debug.c
index 639db0f26e..b4991f71ae 100644
--- a/refs/debug.c
+++ b/refs/debug.c
@@ -143,28 +143,6 @@ static int debug_optimize_required(struct ref_store *ref_store,
 	return res;
 }
 
-static int debug_rename_ref(struct ref_store *ref_store, const char *oldref,
-			    const char *newref, const char *logmsg)
-{
-	struct debug_ref_store *drefs = (struct debug_ref_store *)ref_store;
-	int res = drefs->refs->be->rename_ref(drefs->refs, oldref, newref,
-					      logmsg);
-	trace_printf_key(&trace_refs, "rename_ref: %s -> %s \"%s\": %d\n", oldref, newref,
-		logmsg, res);
-	return res;
-}
-
-static int debug_copy_ref(struct ref_store *ref_store, const char *oldref,
-			  const char *newref, const char *logmsg)
-{
-	struct debug_ref_store *drefs = (struct debug_ref_store *)ref_store;
-	int res =
-		drefs->refs->be->copy_ref(drefs->refs, oldref, newref, logmsg);
-	trace_printf_key(&trace_refs, "copy_ref: %s -> %s \"%s\": %d\n", oldref, newref,
-		logmsg, res);
-	return res;
-}
-
 struct debug_ref_iterator {
 	struct ref_iterator base;
 	struct ref_iterator *iter;
@@ -453,8 +431,6 @@ struct ref_storage_be refs_be_debug = {
 	.optimize = debug_optimize,
 	.optimize_required = debug_optimize_required,
 
-	.rename_ref = debug_rename_ref,
-	.copy_ref = debug_copy_ref,
 
 	.iterator_begin = debug_ref_iterator_begin,
 	.read_raw_ref = debug_read_raw_ref,
diff --git a/refs/files-backend.c b/refs/files-backend.c
index 9e22f62d3f..a00cfc6be5 100644
--- a/refs/files-backend.c
+++ b/refs/files-backend.c
@@ -1623,273 +1623,6 @@ static int files_optimize_required(struct ref_store *ref_store,
 	return 0;
 }
 
-/*
- * People using contrib's git-new-workdir have .git/logs/refs ->
- * /some/other/path/.git/logs/refs, and that may live on another device.
- *
- * IOW, to avoid cross device rename errors, the temporary renamed log must
- * live into logs/refs.
- */
-#define TMP_RENAMED_LOG  "refs/.tmp-renamed-log"
-
-struct rename_cb {
-	const char *tmp_renamed_log;
-	int true_errno;
-};
-
-static int rename_tmp_log_callback(const char *path, void *cb_data)
-{
-	struct rename_cb *cb = cb_data;
-
-	if (rename(cb->tmp_renamed_log, path)) {
-		/*
-		 * rename(a, b) when b is an existing directory ought
-		 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
-		 * Sheesh. Record the true errno for error reporting,
-		 * but report EISDIR to raceproof_create_file() so
-		 * that it knows to retry.
-		 */
-		cb->true_errno = errno;
-		if (errno == ENOTDIR)
-			errno = EISDIR;
-		return -1;
-	} else {
-		return 0;
-	}
-}
-
-static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
-{
-	struct strbuf path = STRBUF_INIT;
-	struct strbuf tmp = STRBUF_INIT;
-	struct rename_cb cb;
-	int ret;
-
-	files_reflog_path(refs, &path, newrefname);
-	files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
-	cb.tmp_renamed_log = tmp.buf;
-	ret = raceproof_create_file(refs, path.buf, rename_tmp_log_callback, &cb);
-	if (ret) {
-		if (errno == EISDIR)
-			error("directory not empty: %s", path.buf);
-		else
-			error("unable to move logfile %s to %s: %s",
-			      tmp.buf, path.buf,
-			      strerror(cb.true_errno));
-	}
-
-	strbuf_release(&path);
-	strbuf_release(&tmp);
-	return ret;
-}
-
-static enum ref_transaction_error write_ref_to_lockfile(struct files_ref_store *refs,
-							struct ref_lock *lock,
-							const struct object_id *oid,
-							struct strbuf *err);
-static int commit_ref_update(struct files_ref_store *refs,
-			     struct ref_lock *lock,
-			     const struct object_id *oid, const char *logmsg,
-			     int flags,
-			     struct strbuf *err);
-
-/*
- * Emit a better error message than lockfile.c's
- * unable_to_lock_message() would in case there is a D/F conflict with
- * another existing reference. If there would be a conflict, emit an error
- * message and return false; otherwise, return true.
- *
- * Note that this function is not safe against all races with other
- * processes, and that's not its job. We'll emit a more verbose error on D/f
- * conflicts if we get past it into lock_ref_oid_basic().
- */
-static int refs_rename_ref_available(struct ref_store *refs,
-			      const char *old_refname,
-			      const char *new_refname)
-{
-	struct string_list skip = STRING_LIST_INIT_NODUP;
-	struct strbuf err = STRBUF_INIT;
-	int ok;
-
-	string_list_insert(&skip, old_refname);
-	ok = !refs_verify_refname_available(refs, new_refname,
-					    NULL, &skip, 0, &err);
-	if (!ok)
-		error("%s", err.buf);
-
-	string_list_clear(&skip, 0);
-	strbuf_release(&err);
-	return ok;
-}
-
-static int files_copy_or_rename_ref(struct ref_store *ref_store,
-			    const char *oldrefname, const char *newrefname,
-			    const char *logmsg, int copy)
-{
-	struct files_ref_store *refs =
-		files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
-	struct object_id orig_oid;
-	int flag = 0, logmoved = 0;
-	struct ref_lock *lock;
-	struct stat loginfo;
-	struct strbuf sb_oldref = STRBUF_INIT;
-	struct strbuf sb_newref = STRBUF_INIT;
-	struct strbuf tmp_renamed_log = STRBUF_INIT;
-	int log, ret;
-	struct strbuf err = STRBUF_INIT;
-
-	files_reflog_path(refs, &sb_oldref, oldrefname);
-	files_reflog_path(refs, &sb_newref, newrefname);
-	files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
-
-	log = !lstat(sb_oldref.buf, &loginfo);
-	if (log && S_ISLNK(loginfo.st_mode)) {
-		ret = error("reflog for %s is a symlink", oldrefname);
-		goto out;
-	}
-
-	if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
-				     RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
-				     &orig_oid, &flag)) {
-		ret = error("refname %s not found", oldrefname);
-		goto out;
-	}
-
-	if (flag & REF_ISSYMREF) {
-		if (copy)
-			ret = error("refname %s is a symbolic ref, copying it is not supported",
-				    oldrefname);
-		else
-			ret = error("refname %s is a symbolic ref, renaming it is not supported",
-				    oldrefname);
-		goto out;
-	}
-	if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
-		ret = 1;
-		goto out;
-	}
-
-	if (!copy && log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
-		ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
-			    oldrefname, strerror(errno));
-		goto out;
-	}
-
-	if (copy && log && copy_file(refs->base.repo, tmp_renamed_log.buf, sb_oldref.buf, 0644)) {
-		ret = error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
-			    oldrefname, strerror(errno));
-		goto out;
-	}
-
-	if (!copy && refs_delete_ref(&refs->base, logmsg, oldrefname,
-			    &orig_oid, REF_NO_DEREF)) {
-		error("unable to delete old %s", oldrefname);
-		goto rollback;
-	}
-
-	/*
-	 * Since we are doing a shallow lookup, oid is not the
-	 * correct value to pass to delete_ref as old_oid. But that
-	 * doesn't matter, because an old_oid check wouldn't add to
-	 * the safety anyway; we want to delete the reference whatever
-	 * its current value.
-	 */
-	if (!copy && refs_resolve_ref_unsafe(&refs->base, newrefname,
-					     RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
-					     NULL, NULL) &&
-	    refs_delete_ref(&refs->base, NULL, newrefname,
-			    NULL, REF_NO_DEREF)) {
-		if (errno == EISDIR) {
-			struct strbuf path = STRBUF_INIT;
-			int result;
-
-			files_ref_path(refs, &path, newrefname);
-			result = remove_empty_directories(&path);
-			strbuf_release(&path);
-
-			if (result) {
-				error("Directory not empty: %s", newrefname);
-				goto rollback;
-			}
-		} else {
-			error("unable to delete existing %s", newrefname);
-			goto rollback;
-		}
-	}
-
-	if (log && rename_tmp_log(refs, newrefname))
-		goto rollback;
-
-	logmoved = log;
-
-	lock = lock_ref_oid_basic(refs, newrefname, &err);
-	if (!lock) {
-		if (copy)
-			error("unable to copy '%s' to '%s': %s", oldrefname, newrefname, err.buf);
-		else
-			error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
-		strbuf_release(&err);
-		goto rollback;
-	}
-	oidcpy(&lock->old_oid, &orig_oid);
-
-	if (write_ref_to_lockfile(refs, lock, &orig_oid, &err) ||
-	    commit_ref_update(refs, lock, &orig_oid, logmsg, 0, &err)) {
-		error("unable to write current sha1 into %s: %s", newrefname, err.buf);
-		strbuf_release(&err);
-		goto rollback;
-	}
-
-	ret = 0;
-	goto out;
-
- rollback:
-	lock = lock_ref_oid_basic(refs, oldrefname, &err);
-	if (!lock) {
-		error("unable to lock %s for rollback: %s", oldrefname, err.buf);
-		strbuf_release(&err);
-		goto rollbacklog;
-	}
-
-	if (write_ref_to_lockfile(refs, lock, &orig_oid, &err) ||
-	    commit_ref_update(refs, lock, &orig_oid, NULL, REF_SKIP_CREATE_REFLOG, &err)) {
-		error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
-		strbuf_release(&err);
-	}
-
- rollbacklog:
-	if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
-		error("unable to restore logfile %s from %s: %s",
-			oldrefname, newrefname, strerror(errno));
-	if (!logmoved && log &&
-	    rename(tmp_renamed_log.buf, sb_oldref.buf))
-		error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
-			oldrefname, strerror(errno));
-	ret = 1;
- out:
-	strbuf_release(&sb_newref);
-	strbuf_release(&sb_oldref);
-	strbuf_release(&tmp_renamed_log);
-
-	return ret;
-}
-
-static int files_rename_ref(struct ref_store *ref_store,
-			    const char *oldrefname, const char *newrefname,
-			    const char *logmsg)
-{
-	return files_copy_or_rename_ref(ref_store, oldrefname,
-				 newrefname, logmsg, 0);
-}
-
-static int files_copy_ref(struct ref_store *ref_store,
-			    const char *oldrefname, const char *newrefname,
-			    const char *logmsg)
-{
-	return files_copy_or_rename_ref(ref_store, oldrefname,
-				 newrefname, logmsg, 1);
-}
-
 static int close_ref_gently(struct ref_lock *lock)
 {
 	if (close_lock_file_gently(&lock->lk))
@@ -2121,71 +1854,6 @@ static enum ref_transaction_error write_ref_to_lockfile(struct files_ref_store *
 	return 0;
 }
 
-/*
- * Commit a change to a loose reference that has already been written
- * to the loose reference lockfile. Also update the reflogs if
- * necessary, using the specified lockmsg (which can be NULL).
- */
-static int commit_ref_update(struct files_ref_store *refs,
-			     struct ref_lock *lock,
-			     const struct object_id *oid, const char *logmsg,
-			     int flags,
-			     struct strbuf *err)
-{
-	files_assert_main_repository(refs, "commit_ref_update");
-
-	clear_loose_ref_cache(refs);
-	if (files_log_ref_write(refs, lock->ref_name, &lock->old_oid, oid, NULL,
-				logmsg, flags, err)) {
-		char *old_msg = strbuf_detach(err, NULL);
-		strbuf_addf(err, "cannot update the ref '%s': %s",
-			    lock->ref_name, old_msg);
-		free(old_msg);
-		unlock_ref(lock);
-		return -1;
-	}
-
-	if (strcmp(lock->ref_name, "HEAD") != 0) {
-		/*
-		 * Special hack: If a branch is updated directly and HEAD
-		 * points to it (may happen on the remote side of a push
-		 * for example) then logically the HEAD reflog should be
-		 * updated too.
-		 * A generic solution implies reverse symref information,
-		 * but finding all symrefs pointing to the given branch
-		 * would be rather costly for this rare event (the direct
-		 * update of a branch) to be worth it.  So let's cheat and
-		 * check with HEAD only which should cover 99% of all usage
-		 * scenarios (even 100% of the default ones).
-		 */
-		int head_flag;
-		const char *head_ref;
-
-		head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
-						   RESOLVE_REF_READING,
-						   NULL, &head_flag);
-		if (head_ref && (head_flag & REF_ISSYMREF) &&
-		    !strcmp(head_ref, lock->ref_name)) {
-			struct strbuf log_err = STRBUF_INIT;
-			if (files_log_ref_write(refs, "HEAD", &lock->old_oid,
-						oid, NULL, logmsg, flags,
-						&log_err)) {
-				error("%s", log_err.buf);
-				strbuf_release(&log_err);
-			}
-		}
-	}
-
-	if (commit_ref(lock)) {
-		strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
-		unlock_ref(lock);
-		return -1;
-	}
-
-	unlock_ref(lock);
-	return 0;
-}
-
 #if defined(NO_SYMLINK_HEAD) || defined(WITH_BREAKING_CHANGES)
 #define create_ref_symlink(a, b) (-1)
 #else
@@ -4468,8 +4136,6 @@ struct ref_storage_be refs_be_files = {
 
 	.optimize = files_optimize,
 	.optimize_required = files_optimize_required,
-	.rename_ref = files_rename_ref,
-	.copy_ref = files_copy_ref,
 
 	.iterator_begin = files_ref_iterator_begin,
 	.read_raw_ref = files_read_raw_ref,
diff --git a/refs/packed-backend.c b/refs/packed-backend.c
index a73fc6aca7..364a912912 100644
--- a/refs/packed-backend.c
+++ b/refs/packed-backend.c
@@ -2164,8 +2164,6 @@ struct ref_storage_be refs_be_packed = {
 	.optimize = packed_optimize,
 	.optimize_required = packed_optimize_required,
 
-	.rename_ref = NULL,
-	.copy_ref = NULL,
 
 	.iterator_begin = packed_ref_iterator_begin,
 	.read_raw_ref = packed_read_raw_ref,
diff --git a/refs/refs-internal.h b/refs/refs-internal.h
index 2746ce5b49..c415ba0a4e 100644
--- a/refs/refs-internal.h
+++ b/refs/refs-internal.h
@@ -470,13 +470,6 @@ typedef int optimize_required_fn(struct ref_store *ref_store,
 				 struct refs_optimize_opts *opts,
 				 bool *required);
 
-typedef int rename_ref_fn(struct ref_store *ref_store,
-			  const char *oldref, const char *newref,
-			  const char *logmsg);
-typedef int copy_ref_fn(struct ref_store *ref_store,
-			  const char *oldref, const char *newref,
-			  const char *logmsg);
-
 /*
  * Iterate over the references in `ref_store` whose names start with
  * `prefix`. `prefix` is matched as a literal string, without regard
@@ -596,8 +589,6 @@ struct ref_storage_be {
 
 	optimize_fn *optimize;
 	optimize_required_fn *optimize_required;
-	rename_ref_fn *rename_ref;
-	copy_ref_fn *copy_ref;
 
 	ref_iterator_begin_fn *iterator_begin;
 	read_raw_ref_fn *read_raw_ref;
diff --git a/refs/reftable-backend.c b/refs/reftable-backend.c
index 72c1596c11..ef3bab69ee 100644
--- a/refs/reftable-backend.c
+++ b/refs/reftable-backend.c
@@ -1798,290 +1798,6 @@ struct write_create_symref_arg {
 	const char *logmsg;
 };
 
-struct write_copy_arg {
-	struct reftable_ref_store *refs;
-	struct reftable_backend *be;
-	const char *oldname;
-	const char *newname;
-	const char *logmsg;
-	int delete_old;
-};
-
-static int write_copy_table(struct reftable_writer *writer, void *cb_data)
-{
-	struct write_copy_arg *arg = cb_data;
-	uint64_t deletion_ts, creation_ts;
-	struct reftable_ref_record old_ref = {0}, refs[2] = {0};
-	struct reftable_log_record old_log = {0}, *logs = NULL;
-	struct reftable_iterator it = {0};
-	struct string_list skip = STRING_LIST_INIT_NODUP;
-	struct ident_split committer_ident = {0};
-	struct strbuf errbuf = STRBUF_INIT;
-	size_t logs_nr = 0, logs_alloc = 0, i;
-	const char *committer_info;
-	int ret;
-
-	committer_info = git_committer_info(0);
-	if (split_ident_line(&committer_ident, committer_info, strlen(committer_info)))
-		BUG("failed splitting committer info");
-
-	if (reftable_stack_read_ref(arg->be->stack, arg->oldname, &old_ref)) {
-		ret = error(_("refname %s not found"), arg->oldname);
-		goto done;
-	}
-	if (old_ref.value_type == REFTABLE_REF_SYMREF) {
-		ret = error(_("refname %s is a symbolic ref, copying it is not supported"),
-			    arg->oldname);
-		goto done;
-	}
-
-	/*
-	 * There's nothing to do in case the old and new name are the same, so
-	 * we exit early in that case.
-	 */
-	if (!strcmp(arg->oldname, arg->newname)) {
-		ret = 0;
-		goto done;
-	}
-
-	/*
-	 * Verify that the new refname is available.
-	 */
-	if (arg->delete_old)
-		string_list_insert(&skip, arg->oldname);
-	ret = refs_verify_refname_available(&arg->refs->base, arg->newname,
-					    NULL, &skip, 0, &errbuf);
-	if (ret < 0) {
-		error("%s", errbuf.buf);
-		goto done;
-	}
-
-	/*
-	 * When deleting the old reference we have to use two update indices:
-	 * once to delete the old ref and its reflog, and once to create the
-	 * new ref and its reflog. They need to be staged with two separate
-	 * indices because the new reflog needs to encode both the deletion of
-	 * the old branch and the creation of the new branch, and we cannot do
-	 * two changes to a reflog in a single update.
-	 */
-	deletion_ts = creation_ts = reftable_stack_next_update_index(arg->be->stack);
-	if (arg->delete_old)
-		creation_ts++;
-	ret = reftable_writer_set_limits(writer, deletion_ts, creation_ts);
-	if (ret < 0)
-		goto done;
-
-	/*
-	 * Add the new reference. If this is a rename then we also delete the
-	 * old reference.
-	 */
-	refs[0] = old_ref;
-	refs[0].refname = xstrdup(arg->newname);
-	refs[0].update_index = creation_ts;
-	if (arg->delete_old) {
-		refs[1].refname = xstrdup(arg->oldname);
-		refs[1].value_type = REFTABLE_REF_DELETION;
-		refs[1].update_index = deletion_ts;
-	}
-	ret = reftable_writer_add_refs(writer, refs, arg->delete_old ? 2 : 1);
-	if (ret < 0)
-		goto done;
-
-	/*
-	 * When deleting the old branch we need to create a reflog entry on the
-	 * new branch name that indicates that the old branch has been deleted
-	 * and then recreated. This is a tad weird, but matches what the files
-	 * backend does.
-	 */
-	if (arg->delete_old) {
-		struct strbuf head_referent = STRBUF_INIT;
-		struct object_id head_oid;
-		int append_head_reflog;
-		unsigned head_type = 0;
-
-		ALLOC_GROW(logs, logs_nr + 1, logs_alloc);
-		memset(&logs[logs_nr], 0, sizeof(logs[logs_nr]));
-		fill_reftable_log_record(&logs[logs_nr], &committer_ident);
-		logs[logs_nr].refname = xstrdup(arg->newname);
-		logs[logs_nr].update_index = deletion_ts;
-		logs[logs_nr].value.update.message =
-			xstrndup(arg->logmsg, reftable_be_write_options(arg->refs)->opts.block_size / 2);
-		memcpy(logs[logs_nr].value.update.old_hash, old_ref.value.val1, GIT_MAX_RAWSZ);
-		logs_nr++;
-
-		ret = reftable_backend_read_ref(arg->be, "HEAD", &head_oid,
-						&head_referent, &head_type);
-		if (ret < 0)
-			goto done;
-		append_head_reflog = (head_type & REF_ISSYMREF) && !strcmp(head_referent.buf, arg->oldname);
-		strbuf_release(&head_referent);
-
-		/*
-		 * The files backend uses `refs_delete_ref()` to delete the old
-		 * branch name, which will append a reflog entry for HEAD in
-		 * case it points to the old branch.
-		 */
-		if (append_head_reflog) {
-			ALLOC_GROW(logs, logs_nr + 1, logs_alloc);
-			logs[logs_nr] = logs[logs_nr - 1];
-			logs[logs_nr].refname = xstrdup("HEAD");
-			logs[logs_nr].value.update.name =
-				xstrdup(logs[logs_nr].value.update.name);
-			logs[logs_nr].value.update.email =
-				xstrdup(logs[logs_nr].value.update.email);
-			logs[logs_nr].value.update.message =
-				xstrdup(logs[logs_nr].value.update.message);
-			logs_nr++;
-		}
-	}
-
-	/*
-	 * Create the reflog entry for the newly created branch.
-	 */
-	ALLOC_GROW(logs, logs_nr + 1, logs_alloc);
-	memset(&logs[logs_nr], 0, sizeof(logs[logs_nr]));
-	fill_reftable_log_record(&logs[logs_nr], &committer_ident);
-	logs[logs_nr].refname = xstrdup(arg->newname);
-	logs[logs_nr].update_index = creation_ts;
-	logs[logs_nr].value.update.message =
-		xstrndup(arg->logmsg, reftable_be_write_options(arg->refs)->opts.block_size / 2);
-	memcpy(logs[logs_nr].value.update.new_hash, old_ref.value.val1, GIT_MAX_RAWSZ);
-	logs_nr++;
-
-	/*
-	 * In addition to writing the reflog entry for the new branch, we also
-	 * copy over all log entries from the old reflog. Last but not least,
-	 * when renaming we also have to delete all the old reflog entries.
-	 */
-	ret = reftable_stack_init_log_iterator(arg->be->stack, &it);
-	if (ret < 0)
-		goto done;
-
-	ret = reftable_iterator_seek_log(&it, arg->oldname);
-	if (ret < 0)
-		goto done;
-
-	while (1) {
-		ret = reftable_iterator_next_log(&it, &old_log);
-		if (ret < 0)
-			goto done;
-		if (ret > 0 || strcmp(old_log.refname, arg->oldname)) {
-			ret = 0;
-			break;
-		}
-		if (reftable_log_record_is_deletion(&old_log))
-			continue;
-
-		free(old_log.refname);
-
-		/*
-		 * Copy over the old reflog entry with the new refname.
-		 */
-		ALLOC_GROW(logs, logs_nr + 1, logs_alloc);
-		logs[logs_nr] = old_log;
-		logs[logs_nr].refname = xstrdup(arg->newname);
-		logs_nr++;
-
-		/*
-		 * Delete the old reflog entry in case we are renaming.
-		 */
-		if (arg->delete_old) {
-			ALLOC_GROW(logs, logs_nr + 1, logs_alloc);
-			memset(&logs[logs_nr], 0, sizeof(logs[logs_nr]));
-			logs[logs_nr].refname = xstrdup(arg->oldname);
-			logs[logs_nr].value_type = REFTABLE_LOG_DELETION;
-			logs[logs_nr].update_index = old_log.update_index;
-			logs_nr++;
-		}
-
-		/*
-		 * Transfer ownership of the log record we're iterating over to
-		 * the array of log records. Otherwise, the pointers would get
-		 * free'd or reallocated by the iterator.
-		 */
-		memset(&old_log, 0, sizeof(old_log));
-	}
-
-	ret = reftable_writer_add_logs(writer, logs, logs_nr);
-	if (ret < 0)
-		goto done;
-
-done:
-	assert(ret != REFTABLE_API_ERROR);
-	reftable_iterator_destroy(&it);
-	string_list_clear(&skip, 0);
-	strbuf_release(&errbuf);
-	for (i = 0; i < logs_nr; i++)
-		reftable_log_record_release(&logs[i]);
-	free(logs);
-	for (i = 0; i < ARRAY_SIZE(refs); i++)
-		reftable_ref_record_release(&refs[i]);
-	reftable_ref_record_release(&old_ref);
-	reftable_log_record_release(&old_log);
-	return ret;
-}
-
-static int reftable_be_rename_ref(struct ref_store *ref_store,
-				  const char *oldrefname,
-				  const char *newrefname,
-				  const char *logmsg)
-{
-	struct reftable_ref_store *refs =
-		reftable_be_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
-	struct write_copy_arg arg = {
-		.refs = refs,
-		.oldname = oldrefname,
-		.newname = newrefname,
-		.logmsg = logmsg,
-		.delete_old = 1,
-	};
-	int ret;
-
-	ret = refs->err;
-	if (ret < 0)
-		goto done;
-
-	ret = backend_for(&arg.be, refs, newrefname, &newrefname, 1);
-	if (ret)
-		goto done;
-	ret = reftable_stack_add(arg.be->stack, &write_copy_table, &arg,
-				 &reftable_be_write_options(refs)->opts);
-
-done:
-	assert(ret != REFTABLE_API_ERROR);
-	return ret;
-}
-
-static int reftable_be_copy_ref(struct ref_store *ref_store,
-				const char *oldrefname,
-				const char *newrefname,
-				const char *logmsg)
-{
-	struct reftable_ref_store *refs =
-		reftable_be_downcast(ref_store, REF_STORE_WRITE, "copy_ref");
-	struct write_copy_arg arg = {
-		.refs = refs,
-		.oldname = oldrefname,
-		.newname = newrefname,
-		.logmsg = logmsg,
-	};
-	int ret;
-
-	ret = refs->err;
-	if (ret < 0)
-		goto done;
-
-	ret = backend_for(&arg.be, refs, newrefname, &newrefname, 1);
-	if (ret)
-		goto done;
-	ret = reftable_stack_add(arg.be->stack, &write_copy_table, &arg,
-				 &reftable_be_write_options(refs)->opts);
-
-done:
-	assert(ret != REFTABLE_API_ERROR);
-	return ret;
-}
-
 struct reftable_reflog_iterator {
 	struct ref_iterator base;
 	struct reftable_ref_store *refs;
@@ -2909,9 +2625,6 @@ struct ref_storage_be refs_be_reftable = {
 	.optimize = reftable_be_optimize,
 	.optimize_required = reftable_be_optimize_required,
 
-	.rename_ref = reftable_be_rename_ref,
-	.copy_ref = reftable_be_copy_ref,
-
 	.iterator_begin = reftable_be_iterator_begin,
 	.read_raw_ref = reftable_be_read_raw_ref,
 	.read_symbolic_ref = reftable_be_read_symbolic_ref,
-- 
2.39.3 (Apple Git-146)
Re: [PATCH v3 0/4] refs: run copy and rename through transactions
#54
Author: Junio C Hamano
Date: Wed, 07 Oct 2026 19:55
81 lines
13531 bytes
Maciej Ciemborowicz <maciej.ciemborowicz@gmail.com> writes:

> Reference copy and rename bypass the transaction API. With files, the
> reference-transaction hook sees only the source deletion; with reftable,
> it sees neither endpoint. This series puts the logical ref updates and
> the reflog history into ordinary transactions so hooks can observe and
> reject the complete operation.
> ...
>  Documentation/githooks.adoc     |  10 +
>  refs.c                          | 200 ++++++++-
>  refs.h                          |  25 ++
>  refs/debug.c                    |  24 --
>  refs/files-backend.c            | 739 +++++++++++++++++---------------
>  refs/packed-backend.c           |   2 -
>  refs/refs-internal.h            |  28 +-
>  refs/reftable-backend.c         | 334 ++-------------
>  t/helper/test-ref-store.c       |  76 ++++
>  t/perf/p1424-ref-copy-rename.sh |  48 +++
>  t/t1424-ref-copy-transaction.sh | 352 +++++++++++++++
>  t/t1425-reflog-transaction.sh   |  59 +++
>  12 files changed, 1206 insertions(+), 691 deletions(-)
>  create mode 100755 t/perf/p1424-ref-copy-rename.sh
>  create mode 100755 t/t1424-ref-copy-transaction.sh
>  create mode 100755 t/t1425-reflog-transaction.sh
>
> Range-diff against v2:
> 1:  d852537d8c < -:  ---------- refs: run copy and rename through transactions
> -:  ---------- > 1:  6d7c146e57 refs: distinguish internal transactions from logical updates
> -:  ---------- > 2:  5c3ec4eb49 refs: support replacing reflogs in a transaction
> -:  ---------- > 3:  77af4e809c refs: run copy and rename through ordinary transactions
> -:  ---------- > 4:  83fa644fb3 refs: remove backend-specific copy and rename callbacks

I do not think I have time to read these humoungous patches, some of
which weigh more than 1000+ lines, with fine toothed comb any time
soon, but when applied to the recent tip of master 6de20f6092 (The
4th batch, 2026-10-06), it seems to break t0600 and t5510.  The
failing tests do not seem to be anything so system specific (and I
am on a GNU/Linux platform that is not anything remarkable).

I wonder what I am doing differently.  Did they pass for you?  Here
are the first failure from these test scripts.

Thanks.

expecting success of 0600.16 'delete fails cleanly if packed-refs.new write fails':
        # Setup and expectations are similar to the test above.
        prefix=refs/failed-packed-refs &&
        git update-ref $prefix/foo $C &&
        git pack-refs --all &&
        git update-ref $prefix/foo $D &&
        git for-each-ref $prefix >unchanged &&
        # This should not happen in practice, but it is an easy way to get a
        # reliable error (we open with create_tempfile(), which uses O_EXCL).
        : >.git/packed-refs.new &&
        test_when_finished "rm -f .git/packed-refs.new" &&
        test_must_fail git update-ref -d $prefix/foo &&
        git for-each-ref $prefix >actual &&
        test_cmp unchanged actual

test_must_fail: command succeeded: git update-ref -d refs/failed-packed-refs/foo
not ok 16 - delete fails cleanly if packed-refs.new write fails

expecting success of 5510.35 'fetch --prune fails to delete branches':
        git clone . prune-fail &&
        (
                cd prune-fail &&
                git update-ref refs/remotes/origin/extrabranch main &&
                git pack-refs --all &&
                : this will prevent --prune from locking packed-refs for deleting refs, but adding loose refs still succeeds  &&
                >.git/packed-refs.new &&

                test_must_fail git fetch --prune origin
        )

Cloning into 'prune-fail'...
done.
From /usr/local/google/home/jch/w/git.git/t/trash directory.t5510-fetch/.
 - [deleted]         (none)     -> origin/extrabranch
test_must_fail: command succeeded: git fetch --prune origin
not ok 35 - fetch --prune fails to delete branches
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads