threads / patch / 62998

v2, 7 partsrefs/files: remove redundant check in split_symref_update()

Subject: [PATCH v2 1/7] refs/files: remove redundant check in split_symref_update()

## tl;dr

20 messages between Feb 25, 2025 and Mar 5, 2025. Diffs are folded; open one to read it.

replies: 19people: 3as markdown or json

Karthik Nayak· Feb 25, 2025, 09:29 UTC · lore

[PATCH v2 0/7] refs: introduce support for partial reference transactions

 Documentation/git-update-ref.adoc |  21 +-
 builtin/update-ref.c              |  74 +++++-
 refs.c                            | 101 ++++++--
 refs.h                            |  78 ++++--
 refs/files-backend.c              | 260 ++++++++------------
 refs/packed-backend.c             |  70 +++---
 refs/refs-internal.h              |  22 +-
 refs/reftable-backend.c           | 496 +++++++++++++++++++-------------------
 t/t1400-update-ref.sh             | 216 +++++++++++++++++
 9 files changed, 849 insertions(+), 489 deletions(-)
Karthik Nayak (7):
      refs/files: remove redundant check in split_symref_update()
      refs: move duplicate refname update check to generic layer
      refs/files: remove duplicate duplicates check
      refs/reftable: extract code from the transaction preparation
      refs: introduce enum-based transaction error types
      refs: implement partial reference transaction support
      update-ref: add --allow-partial flag for stdin mode

Git's reference updates are traditionally all or nothing - when updating multiple references in a transaction, either all updates succeed or none do. While this behavior is generally desirable, it can be limiting in certain scenarios, particularly with the reftable backend where batching multiple reference updates is more efficient than performing them sequentially.

This series introduces support for partial reference transactions, allowing individual reference updates to fail while letting others proceed. This capability is exposed through git-update-ref's `--allow-partial` flag, which can be used in `--stdin` mode to batch updates and handle failures gracefully.

The changes are structured to carefully build up this functionality:

First, we clean up and consolidate the reference update checking logic. This includes removing duplicate checks in the files backend and moving refname tracking to the generic layer, which simplifies the codebase and prepares it for the new feature.

We then restructure the reftable backend's transaction preparation code, extracting the update validation logic into a dedicated function. This not only improves code organization but sets the stage for implementing partial transaction support.

To ensure we only skip errors which are user-oriented, we introduce typed errors for transactions with 'enum transaction_error'. We extend the existing errors to include other scenarios and use this new errors throughout the refs code.

With this groundwork in place, we implement the core partial transaction support in the refs subsystem. This adds the necessary infrastructure to track and report rejected updates while allowing transactions to proceed. All reference backends are modified to support this behavior when enabled.

Finally, we expose this functionality to users through git-update-ref(1)'s `--allow-partial` flag, complete with test coverage and documentation. The flag is specifically limited to `--stdin` mode where batching multiple updates is most relevant.

This enhancement improves Git's flexibility in handling reference updates while maintaining the safety of atomic transactions by default. It's particularly valuable for tools and workflows that need to handle reference update failures gracefully without abandoning the entire batch of updates.

This series is based on top of b838bf1938 (Merge branch 'master' of https://github.com/j6t/gitk, 2025-02-20) with Patrick's series 'refs: batch refname availability checks' [1] merged in.

[1]: https://lore.kernel.org/all/20250217-pks-update-ref-optimization-v1-0-a2b6d87a24af@pks.im/
---
Changes in v2:
- Introduce and use structured errors. This consolidates the errors
  and their handling between the ref backends.
- In the previous version, we skipped over all failures. This include
  system failures such as low memory or IO problems. Let's instead, only
  skip user-oriented failures, such as invalid old OID and so on.
- Change the rejection function name to `ref_transaction_set_rejected()`.
- Modify the commit messages and documentation to be a little more
  verbose.
- Link to v1: https://lore.kernel.org/r/20250207-245-partially-atomic-ref-updates-v1-0-e6a3690ff23a@gmail.com
Range-diff versus v1:
1:  e48e562f27 ! 1:  4a1b748e7a refs/files: remove duplicate check in `split_symref_update()`
    @@ Metadata
     Author: Karthik Nayak <karthik.188@gmail.com>
     
      ## Commit message ##
    -    refs/files: remove duplicate check in `split_symref_update()`
    +    refs/files: remove redundant check in split_symref_update()
     
    -    In split_symref_update(), there were two redundant checks:
    -       - At the start: checking if refname exists in `affected_refnames`.
    -       - After adding refname: checking if the item added to
    -         `affected_refnames` contains the util field.
    +    In `split_symref_update()`, there were two checks for duplicate
    +    refnames:
     
    -    Remove the second check since the first one already prevents duplicate
    -    refnames from being added to the transaction updates.
    +      - At the start, `string_list_has_string()` ensures the refname is not
    +        already in `affected_refnames`, preventing duplicates from being
    +        added.
     
    -    Since this is the only place that utilizes the `item->util` value, avoid
    -    setting the value in the first place and cleanup code around it.
    +      - After adding the refname, another check verifies whether the newly
    +        inserted item has a `util` value.
    +
    +    The second check is unnecessary because the first one guarantees that
    +    `string_list_insert()` will never encounter a preexisting entry.
    +
    +    Since `item->util` is only used in this context, remove the assignment and
    +    simplify the surrounding code.
     
         Signed-off-by: Karthik Nayak <karthik.188@gmail.com>
     
2:  b5efdd3149 ! 2:  1cfb4f91b5 refs: move duplicate refname update check to generic layer
    @@ Commit message
     
           - Add a `string_list` field `refnames` to `ref_transaction` to contain
             all the references in a transaction. This field is updated whenever
    -        a new update is added.
    +        a new update is added via `ref_transaction_add_update`, so manual
    +        additions in reference backends are dropped.
     
           - Modify the backends to use this field internally as needed. The
             backends need to check if an update for refname already exists when
             splitting symrefs or adding an update for 'HEAD'.
     
    -      - In the reftable backend, in `reftable_be_transaction_prepare()`,
    -        move the instance of `string_list_has_string()` above
    -        `ref_transaction_add_update()` to check before the reference is
    -        added.
    +      - In the reftable backend, within `reftable_be_transaction_prepare()`,
    +        move the `string_list_has_string()` check above
    +        `ref_transaction_add_update()`. Since `ref_transaction_add_update()`
    +        automatically adds the refname to `transaction->refnames`,
    +        performing the check after will always return true, so we perform
    +        the check before adding the update.
     
         This helps reduce duplication of functionality between the backends and
         makes it easier to make changes in a more centralized manner.
    @@ refs/files-backend.c: static int split_symref_update(struct ref_update *update,
      	return 0;
      }
      
    -@@ refs/files-backend.c: struct files_transaction_backend_data {
    - static int lock_ref_for_update(struct files_ref_store *refs,
    - 			       struct ref_update *update,
    +@@ refs/files-backend.c: static int lock_ref_for_update(struct files_ref_store *refs,
      			       struct ref_transaction *transaction,
    --			       const char *head_ref,
    + 			       const char *head_ref,
    + 			       struct string_list *refnames_to_check,
     -			       struct string_list *affected_refnames,
    --			       struct strbuf *err)
    -+			       const char *head_ref, struct strbuf *err)
    + 			       struct strbuf *err)
      {
      	struct strbuf referent = STRBUF_INIT;
    - 	int mustexist = ref_update_expects_existing_old_ref(update);
     @@ refs/files-backend.c: static int lock_ref_for_update(struct files_ref_store *refs,
      		update->flags |= REF_DELETING;
      
    @@ refs/files-backend.c: static int lock_ref_for_update(struct files_ref_store *ref
      		lock->count++;
      	} else {
      		ret = lock_raw_ref(refs, update->refname, mustexist,
    --				   affected_refnames,
    -+				   &transaction->refnames,
    - 				   &lock, &referent,
    - 				   &update->type, err);
    +-				   refnames_to_check, affected_refnames,
    +-				   &lock, &referent,
    +-				   &update->type, err);
    ++				   refnames_to_check, &transaction->refnames,
    ++				   &lock, &referent, &update->type, err);
      		if (ret) {
    + 			char *reason;
    + 
     @@ refs/files-backend.c: static int lock_ref_for_update(struct files_ref_store *refs,
      			 * of processing the split-off update, so we
      			 * don't have to do it here.
    @@ refs/files-backend.c: static int files_transaction_prepare(struct ref_store *ref
      	size_t i;
      	int ret = 0;
     -	struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
    + 	struct string_list refnames_to_check = STRING_LIST_INIT_NODUP;
      	char *head_ref = NULL;
      	int head_type;
    - 	struct files_transaction_backend_data *backend_data;
     @@ refs/files-backend.c: static int files_transaction_prepare(struct ref_store *ref_store,
      	transaction->backend_data = backend_data;
      
    @@ refs/files-backend.c: static int files_transaction_prepare(struct ref_store *ref
      
      	/*
     @@ refs/files-backend.c: static int files_transaction_prepare(struct ref_store *ref_store,
    - 		struct ref_update *update = transaction->updates[i];
      
      		ret = lock_ref_for_update(refs, update, transaction,
    --					  head_ref, &affected_refnames, err);
    -+					  head_ref, err);
    + 					  head_ref, &refnames_to_check,
    +-					  &affected_refnames, err);
    ++					  err);
      		if (ret)
      			goto cleanup;
      
    +@@ refs/files-backend.c: static int files_transaction_prepare(struct ref_store *ref_store,
    + 	 * So instead, we accept the race for now.
    + 	 */
    + 	if (refs_verify_refnames_available(refs->packed_ref_store, &refnames_to_check,
    +-					   &affected_refnames, NULL, 0, err)) {
    ++					   &transaction->refnames, NULL, 0, err)) {
    + 		ret = TRANSACTION_NAME_CONFLICT;
    + 		goto cleanup;
    + 	}
     @@ refs/files-backend.c: static int files_transaction_prepare(struct ref_store *ref_store,
      
      cleanup:
      	free(head_ref);
     -	string_list_clear(&affected_refnames, 0);
    + 	string_list_clear(&refnames_to_check, 0);
      
      	if (ret)
    - 		files_transaction_cleanup(refs, transaction);
    -@@ refs/files-backend.c: static int files_transaction_finish_initial(struct files_ref_store *refs,
    - {
    - 	size_t i;
    - 	int ret = 0;
    --	struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
    - 	struct ref_transaction *packed_transaction = NULL;
    - 	struct ref_transaction *loose_transaction = NULL;
    - 
     @@ refs/files-backend.c: static int files_transaction_finish_initial(struct files_ref_store *refs,
      	if (transaction->state != REF_TRANSACTION_PREPARED)
      		BUG("commit called for transaction that is not prepared");
    @@ refs/files-backend.c: static int files_transaction_finish_initial(struct files_r
      		BUG("initial ref transaction called with existing refs");
      
      	packed_transaction = ref_store_transaction_begin(refs->packed_ref_store,
    -@@ refs/files-backend.c: static int files_transaction_finish_initial(struct files_ref_store *refs,
    - 			BUG("initial ref transaction with old_sha1 set");
    - 
    - 		if (refs_verify_refname_available(&refs->base, update->refname,
    --						  &affected_refnames, NULL, 1, err)) {
    -+						  &transaction->refnames, NULL, 1, err)) {
    - 			ret = TRANSACTION_NAME_CONFLICT;
    - 			goto cleanup;
    - 		}
    -@@ refs/files-backend.c: static int files_transaction_finish_initial(struct files_ref_store *refs,
    - 	if (packed_transaction)
    - 		ref_transaction_free(packed_transaction);
    - 	transaction->state = REF_TRANSACTION_CLOSED;
    --	string_list_clear(&affected_refnames, 0);
    - 	return ret;
    - }
    - 
     
      ## refs/packed-backend.c ##
     @@ refs/packed-backend.c: int is_packed_transaction_needed(struct ref_store *ref_store,
    @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_s
      		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 affected_refnames = STRING_LIST_INIT_NODUP;
    + 	struct string_list refnames_to_check = STRING_LIST_INIT_NODUP;
      	struct reftable_transaction_data *tx_data = NULL;
      	struct reftable_backend *be;
    - 	struct object_id head_oid;
     @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_store *ref_store,
      						 transaction->updates[i], err);
      		if (ret)
    @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_s
      		}
      
      		ret = reftable_backend_read_ref(be, rewritten_ref,
    -@@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_store *ref_store,
    - 			 * at a later point.
    - 			 */
    - 			ret = refs_verify_refname_available(ref_store, u->refname,
    --							    &affected_refnames, NULL,
    -+							    &transaction->refnames, NULL,
    - 							    transaction->flags & REF_TRANSACTION_FLAG_INITIAL,
    - 							    err);
    - 			if (ret < 0)
     @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_store *ref_store,
      				if (!strcmp(rewritten_ref, "HEAD"))
      					new_flags |= REF_UPDATE_VIA_HEAD;
    @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_s
      			}
      		}
      
    +@@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_store *ref_store,
    + 	}
    + 
    + 	string_list_sort(&refnames_to_check);
    +-	ret = refs_verify_refnames_available(ref_store, &refnames_to_check, &affected_refnames, NULL,
    ++	ret = refs_verify_refnames_available(ref_store, &refnames_to_check,
    ++					     &transaction->refnames, NULL,
    + 					     transaction->flags & REF_TRANSACTION_FLAG_INITIAL,
    + 					     err);
    + 	if (ret < 0)
     @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_store *ref_store,
      			strbuf_addf(err, _("reftable: transaction prepare: %s"),
      				    reftable_error_str(ret));
    @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_s
     -	string_list_clear(&affected_refnames, 0);
      	strbuf_release(&referent);
      	strbuf_release(&head_referent);
    - 
    + 	string_list_clear(&refnames_to_check, 0);
3:  1f1c261afd = 3:  91e96c9048 refs/files: remove duplicate duplicates check
4:  556fd87651 ! 4:  c47a020dc5 refs/reftable: extract code from the transaction preparation
    @@ refs/reftable-backend.c: static int queue_transaction_update(struct reftable_ref
      	return 0;
      }
      
    -+static int prepare_single_update(struct ref_store *ref_store,
    -+				 struct reftable_ref_store *refs,
    ++static int prepare_single_update(struct reftable_ref_store *refs,
     +				 struct reftable_transaction_data *tx_data,
     +				 struct ref_transaction *transaction,
     +				 struct reftable_backend *be,
     +				 struct ref_update *u,
    ++				 struct string_list *refnames_to_check,
     +				 unsigned int head_type,
     +				 struct strbuf *head_referent,
     +				 struct strbuf *referent,
    @@ refs/reftable-backend.c: static int queue_transaction_update(struct reftable_ref
     +		 * can output a proper error message instead of failing
     +		 * at a later point.
     +		 */
    -+		ret = refs_verify_refname_available(ref_store, u->refname,
    -+						    &transaction->refnames, NULL,
    -+						    transaction->flags & REF_TRANSACTION_FLAG_INITIAL,
    -+						    err);
    -+		if (ret < 0)
    -+			return ret;
    ++		string_list_append(refnames_to_check, u->refname);
     +
     +		/*
     +		 * There is no need to write the reference deletion
    @@ refs/reftable-backend.c: static int queue_transaction_update(struct reftable_ref
     +	if (ret > 0) {
     +		/* The reference does not exist, but we expected it to. */
     +		strbuf_addf(err, _("cannot lock ref '%s': "
    ++
    ++
     +				   "unable to resolve reference '%s'"),
     +			    ref_update_original_update_refname(u), u->refname);
     +		return -1;
    @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_s
     -		 * stack.
     -		 */
     -		ret = backend_for(&be, refs, u->refname, &rewritten_ref, 0);
    -+		ret = prepare_single_update(ref_store, refs, tx_data,
    -+					    transaction, be,
    -+					    transaction->updates[i], head_type,
    ++		ret = prepare_single_update(refs, tx_data, transaction, be,
    ++					    transaction->updates[i],
    ++					    &refnames_to_check, head_type,
     +					    &head_referent, &referent, err);
      		if (ret)
      			goto done;
    @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_s
     -			 * can output a proper error message instead of failing
     -			 * at a later point.
     -			 */
    --			ret = refs_verify_refname_available(ref_store, u->refname,
    --							    &transaction->refnames, NULL,
    --							    transaction->flags & REF_TRANSACTION_FLAG_INITIAL,
    --							    err);
    --			if (ret < 0)
    --				goto done;
    +-			string_list_append(&refnames_to_check, u->refname);
     -
     -			/*
     -			 * There is no need to write the reference deletion
    @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_s
     -		}
      	}
      
    - 	transaction->backend_data = tx_data;
    + 	string_list_sort(&refnames_to_check);
-:  ---------- > 5:  ff7235f2b8 refs: introduce enum-based transaction error types
5:  14b9657c99 ! 6:  74dce2ea61 refs: implement partial reference transaction support
    @@ Commit message
     
         Git's reference transactions are all-or-nothing: either all updates
         succeed, or none do. While this atomic behavior is generally desirable,
    -    it can be suboptimal when using the reftable backend, where batching
    -    multiple reference updates into a single transaction is more efficient
    -    than performing them sequentially.
    +    it can be suboptimal especially when using the reftable backend, where
    +    batching multiple reference updates into a single transaction is more
    +    efficient than performing them sequentially.
     
    -    Introduce partial transaction support through a new flag
    -    `REF_TRANSACTION_ALLOW_PARTIAL`. When this flag is set, individual
    -    reference updates that would normally fail the entire transaction are
    -    instead marked as rejected while allowing other updates to proceed. This
    -    provides more flexibility while maintaining transactional integrity
    -    where needed.
    +    Introduce partial transaction support with a new flag,
    +    'REF_TRANSACTION_ALLOW_PARTIAL'. When enabled, this flag allows
    +    individual reference updates that would typically cause the entire
    +    transaction to fail due to non-system-related errors to be marked as
    +    rejected while permitting other updates to proceed. Non-system-related
    +    errors include issues caused by user-provided input values, whereas
    +    system-related errors, such as I/O failures or memory issues, continue
    +    to result in a full transaction failure. This approach enhances
    +    flexibility while preserving transactional integrity where necessary.
     
         The implementation introduces several key components:
     
    -      - Add 'rejected' and 'rejection_err' fields to struct `ref_update` to
    -        track failed updates and their failure reasons.
    +      - Add 'rejection_err' field to struct `ref_update` to track failed
    +        updates with failure reason.
     
           - Modify reference backends (files, packed, reftable) to handle
    -        partial transactions by using `ref_transaction_add_rejection()`
    +        partial transactions by using `ref_transaction_set_rejected()`
             instead of failing the entire transaction when
             `REF_TRANSACTION_ALLOW_PARTIAL` is set.
     
    @@ Commit message
         Signed-off-by: Karthik Nayak <karthik.188@gmail.com>
     
      ## refs.c ##
    -@@ refs.c: void ref_transaction_free(struct ref_transaction *transaction)
    - 		free(transaction->updates[i]->committer_info);
    - 		free((char *)transaction->updates[i]->new_target);
    - 		free((char *)transaction->updates[i]->old_target);
    -+		strbuf_release(&transaction->updates[i]->rejection_err);
    - 		free(transaction->updates[i]);
    - 	}
    - 	string_list_clear(&transaction->refnames, 0);
     @@ refs.c: void ref_transaction_free(struct ref_transaction *transaction)
      	free(transaction);
      }
      
    -+void ref_transaction_add_rejection(struct ref_transaction *transaction,
    -+				   size_t update_idx, struct strbuf *err)
    ++void ref_transaction_set_rejected(struct ref_transaction *transaction,
    ++				  size_t update_idx,
    ++				  enum transaction_error err)
     +{
    -+	struct ref_update *update = transaction->updates[update_idx];
    -+	update->rejected = 1;
    -+	strbuf_addbuf(&update->rejection_err, err);
    ++	if (update_idx >= transaction->nr)
    ++		BUG("trying to set rejection on invalid update index");
    ++	transaction->updates[update_idx]->rejection_err = err;
     +}
     +
      struct ref_update *ref_transaction_add_update(
      		struct ref_transaction *transaction,
      		const char *refname, unsigned int flags,
     @@ refs.c: struct ref_update *ref_transaction_add_update(
    + 	transaction->updates[transaction->nr++] = update;
      
      	update->flags = flags;
    ++	update->rejection_err = TRANSACTION_OK;
      
    -+	strbuf_init(&update->rejection_err, 0);
    -+
      	update->new_target = xstrdup_or_null(new_target);
      	update->old_target = xstrdup_or_null(old_target);
    - 	if ((flags & REF_HAVE_NEW) && new_oid)
     @@ refs.c: void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
      	}
      }
    @@ refs.c: void ref_transaction_for_each_queued_update(struct ref_transaction *tran
     +	for (size_t i = 0; i < transaction->nr; i++) {
     +		struct ref_update *update = transaction->updates[i];
     +
    -+		if (!update->rejected)
    ++		if (!update->rejection_err)
     +			continue;
     +
     +		cb(update->refname,
     +		   (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
     +		   (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
     +		   update->old_target, update->new_target,
    -+		   &update->rejection_err, cb_data);
    ++		   update->rejection_err, cb_data);
     +	}
     +}
     +
    @@ refs.h: void ref_transaction_for_each_queued_update(struct ref_transaction *tran
     +							 const struct object_id *new_oid,
     +							 const char *old_target,
     +							 const char *new_target,
    -+							 const struct strbuf *reason,
    ++							 enum transaction_error err,
     +							 void *cb_data);
     +void ref_transaction_for_each_rejected_update(struct ref_transaction *transaction,
     +					      ref_transaction_for_each_rejected_update_fn cb,
    @@ refs.h: void ref_transaction_for_each_queued_update(struct ref_transaction *tran
     
      ## refs/files-backend.c ##
     @@ refs/files-backend.c: static int files_transaction_prepare(struct ref_store *ref_store,
    - 
      		ret = lock_ref_for_update(refs, update, transaction,
    - 					  head_ref, err);
    + 					  head_ref, &refnames_to_check,
    + 					  err);
     -		if (ret)
     +		if (ret) {
    -+			if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL) {
    -+				ref_transaction_add_rejection(transaction, i, err);
    ++			if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL &&
    ++			    ret != TRANSACTION_GENERIC_ERROR) {
    ++				ref_transaction_set_rejected(transaction, i, ret);
     +
     +				strbuf_setlen(err, 0);
    -+				ret = 0;
    ++				ret = TRANSACTION_OK;
     +
     +				continue;
     +			}
      			goto cleanup;
     +		}
    -+
      
      		if (update->flags & REF_DELETING &&
      		    !(update->flags & REF_LOG_ONLY) &&
    @@ refs/packed-backend.c
     @@ refs/packed-backend.c: static int packed_ref_store_remove_on_disk(struct ref_store *ref_store,
       * remain locked when it is done.
       */
    - static int write_with_updates(struct packed_ref_store *refs,
    --			      struct string_list *updates,
    -+			      struct ref_transaction *transaction,
    - 			      struct strbuf *err)
    + static enum transaction_error write_with_updates(struct packed_ref_store *refs,
    +-						 struct string_list *updates,
    ++						 struct ref_transaction *transaction,
    + 						 struct strbuf *err)
      {
    + 	enum transaction_error ret = TRANSACTION_GENERIC_ERROR;
     +	struct string_list *updates = &transaction->refnames;
      	struct ref_iterator *iter = NULL;
      	size_t i;
      	int ok;
    -@@ refs/packed-backend.c: static int write_with_updates(struct packed_ref_store *refs,
    - 					strbuf_addf(err, "cannot update ref '%s': "
    +@@ refs/packed-backend.c: static enum transaction_error write_with_updates(struct packed_ref_store *refs,
      						    "reference already exists",
      						    update->refname);
    + 					ret = TRANSACTION_CREATE_EXISTS;
     +
     +					if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL) {
    -+						ref_transaction_add_rejection(transaction, i, err);
    ++						ref_transaction_set_rejected(transaction, i, ret);
     +						strbuf_setlen(err, 0);
    ++						ret = 0;
     +						continue;
     +					}
     +
      					goto error;
      				} else if (!oideq(&update->old_oid, iter->oid)) {
      					strbuf_addf(err, "cannot update ref '%s': "
    -@@ refs/packed-backend.c: static int write_with_updates(struct packed_ref_store *refs,
    - 						    update->refname,
    +@@ refs/packed-backend.c: static enum transaction_error write_with_updates(struct packed_ref_store *refs,
      						    oid_to_hex(iter->oid),
      						    oid_to_hex(&update->old_oid));
    + 					ret = TRANSACTION_INCORRECT_OLD_VALUE;
     +
     +					if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL) {
    -+						ref_transaction_add_rejection(transaction, i, err);
    ++						ref_transaction_set_rejected(transaction, i, ret);
     +						strbuf_setlen(err, 0);
    ++						ret = 0;
     +						continue;
     +					}
     +
      					goto error;
      				}
      			}
    -@@ refs/packed-backend.c: static int write_with_updates(struct packed_ref_store *refs,
    - 					    "reference is missing but expected %s",
    +@@ refs/packed-backend.c: static enum transaction_error write_with_updates(struct packed_ref_store *refs,
      					    update->refname,
      					    oid_to_hex(&update->old_oid));
    + 				return TRANSACTION_NONEXISTENT_REF;
     +
     +				if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL) {
    -+					ref_transaction_add_rejection(transaction, i, err);
    ++					ref_transaction_set_rejected(transaction, i, ret);
     +					strbuf_setlen(err, 0);
    ++					ret = 0;
     +					continue;
     +				}
     +
      				goto error;
      			}
      		}
    +@@ refs/packed-backend.c: static enum transaction_error write_with_updates(struct packed_ref_store *refs,
    + write_error:
    + 	strbuf_addf(err, "error writing to %s: %s",
    + 		    get_tempfile_path(refs->tempfile), strerror(errno));
    ++	ret = TRANSACTION_GENERIC_ERROR;
    + 
    + error:
    + 	ref_iterator_free(iter);
     @@ refs/packed-backend.c: static int packed_transaction_prepare(struct ref_store *ref_store,
      		data->own_lock = 1;
      	}
      
    --	if (write_with_updates(refs, &transaction->refnames, err))
    -+	if (write_with_updates(refs, transaction, err))
    +-	ret = write_with_updates(refs, &transaction->refnames, err);
    ++	ret = write_with_updates(refs, transaction, err);
    + 	if (ret)
      		goto failure;
      
    - 	transaction->state = REF_TRANSACTION_PREPARED;
     
      ## refs/refs-internal.h ##
    -@@
    - 
    - #include "refs.h"
    - #include "iterator.h"
    -+#include "strbuf.h"
    - #include "string-list.h"
    - 
    - struct fsck_options;
     @@ refs/refs-internal.h: struct ref_update {
      	 */
    - 	unsigned int index;
    + 	uint64_t index;
      
     +	/*
    -+	 * Used in partial transactions to mark a given update as rejected,
    -+	 * with rejection reason.
    ++	 * Used in partial transactions to mark if a given update was rejected.
     +	 */
    -+	unsigned int rejected;
    -+	struct strbuf rejection_err;
    ++	enum transaction_error rejection_err;
     +
      	/*
      	 * If this ref_update was split off of a symref update via
    @@ refs/refs-internal.h: int refs_read_raw_ref(struct ref_store *ref_store, const c
     + * Mark a given update as rejected with a given reason. To be used in conjuction
     + * with the `REF_TRANSACTION_ALLOW_PARTIAL` flag to allow partial transactions.
     + */
    -+void ref_transaction_add_rejection(struct ref_transaction *transaction,
    -+				   size_t update_idx, struct strbuf *err);
    ++void ref_transaction_set_rejected(struct ref_transaction *transaction,
    ++				  size_t update_idx,
    ++				  enum transaction_error err);
     +
      /*
       * Add a ref_update with the specified properties to transaction, and
    @@ refs/refs-internal.h: int refs_read_raw_ref(struct ref_store *ref_store, const c
     
      ## refs/reftable-backend.c ##
     @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_store *ref_store,
    - 					    transaction, be,
    - 					    transaction->updates[i], head_type,
    + 					    transaction->updates[i],
    + 					    &refnames_to_check, head_type,
      					    &head_referent, &referent, err);
     -		if (ret)
    -+
     +		if (ret) {
    -+			if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL) {
    -+				ref_transaction_add_rejection(transaction, i, err);
    ++			if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL &&
    ++			    ret != TRANSACTION_GENERIC_ERROR) {
    ++				ref_transaction_set_rejected(transaction, i, ret);
     +
     +				strbuf_setlen(err, 0);
    -+				ret = 0;
    ++				ret = TRANSACTION_OK;
     +
     +				continue;
     +			}
    @@ refs/reftable-backend.c: static int reftable_be_transaction_prepare(struct ref_s
     +		}
      	}
      
    - 	transaction->backend_data = tx_data;
    + 	string_list_sort(&refnames_to_check);
6:  8c90e4201a ! 7:  d79851e041 update-ref: add --allow-partial flag for stdin mode
    @@ Commit message
     
         Signed-off-by: Karthik Nayak <karthik.188@gmail.com>
     
    - ## Documentation/git-update-ref.txt ##
    -@@ Documentation/git-update-ref.txt: git-update-ref - Update the object name stored in a ref safely
    + ## Documentation/git-update-ref.adoc ##
    +@@ Documentation/git-update-ref.adoc: git-update-ref - Update the object name stored in a ref safely
    + 
      SYNOPSIS
      --------
    - [verse]
    +-[verse]
     -'git update-ref' [-m <reason>] [--no-deref] (-d <ref> [<old-oid>] | [--create-reflog] <ref> <new-oid> [<old-oid>] | --stdin [-z])
    -+'git update-ref' [-m <reason>] [--no-deref] (-d <ref> [<old-oid>] | [--create-reflog] <ref> <new-oid> [<old-oid>] | --stdin [-z] [--allow-partial])
    ++[synopsis]
    ++git update-ref [-m <reason>] [--no-deref] -d <ref> [<old-oid>]
    ++	       [-m <reason>] [--no-deref] [--create-reflog] <ref> <new-oid> [<old-oid>]
    ++               [-m <reason>] [--no-deref] --stdin [-z] [--allow-partial]
      
      DESCRIPTION
      -----------
    -@@ Documentation/git-update-ref.txt: performs all modifications together.  Specify commands of the form:
    +@@ Documentation/git-update-ref.adoc: performs all modifications together.  Specify commands of the form:
      With `--create-reflog`, update-ref will create a reflog for each ref
      even if one would not ordinarily be created.
      
    -+With `--allow-partial`, update-ref will process the transaction even if
    -+some of the updates fail, allowing remaining updates to be applied.
    -+Failed updates will be printed in the following format:
    ++With `--allow-partial`, update-ref continues executing the transaction even if
    ++some updates fail due to invalid or incorrect user input, applying only the
    ++successful updates. Errors resulting from user-provided input are treated as
    ++non-system-related and do not cause the entire transaction to be aborted.
    ++However, system-related errors—such as I/O failures or memory issues—will still
    ++result in a full failure. Additionally, errors like F/D conflicts are batched
    ++for performance optimization and will also cause a full failure. Any failed
    ++updates will be reported in the following format:
     +
     +	rejected SP (<old-oid> | <old-target>) SP (<new-oid> | <new-target>) SP <rejection-reason> LF
     +
      Quote fields containing whitespace as if they were strings in C source
      code; i.e., surrounded by double-quotes and with backslash escapes.
      Use 40 "0" characters or the empty string to specify a zero value.  To
    -@@ Documentation/git-update-ref.txt: quoting:
    +@@ Documentation/git-update-ref.adoc: quoting:
      In this format, use 40 "0" to specify a zero value, and use the empty
      string to specify a missing value.
      
    @@ builtin/update-ref.c: static void parse_cmd_abort(struct ref_transaction *transa
     +				const struct object_id *new_oid,
     +				const char *old_target,
     +				const char *new_target,
    -+				const struct strbuf *reason,
    ++				enum transaction_error err,
     +				void *cb_data UNUSED)
     +{
     +	struct strbuf sb = STRBUF_INIT;
     +	char space = ' ';
    ++	const char *reason = "";
    ++
    ++	switch (err) {
    ++	case TRANSACTION_NAME_CONFLICT:
    ++		reason = _("refname conflict");
    ++		break;
    ++	case TRANSACTION_CREATE_EXISTS:
    ++		reason = _("reference already exists");
    ++		break;
    ++	case TRANSACTION_NONEXISTENT_REF:
    ++		reason = _("reference does not exist");
    ++		break;
    ++	case TRANSACTION_INCORRECT_OLD_VALUE:
    ++		reason = _("incorrect old value provided");
    ++		break;
    ++	case TRANSACTION_INVALID_NEW_VALUE:
    ++		reason = _("invalid new value provided");
    ++		break;
    ++	case TRANSACTION_EXPECTED_SYMREF:
    ++		reason = _("expected symref but found regular ref");
    ++		break;
    ++	default:
    ++		reason = _("unkown failure");
    ++	}
     +
     +	if (!line_termination)
     +		space = line_termination;
    @@ builtin/update-ref.c: static void parse_cmd_abort(struct ref_transaction *transa
     +	strbuf_addf(&sb, "rejected%c%s%c%s%c%c%s%c%s%c", space,
     +		    refname, space, new_oid ? oid_to_hex(new_oid) : new_target,
     +		    space, space, old_oid ? oid_to_hex(old_oid) : old_target,
    -+		    space, reason->buf, line_termination);
    ++		    space, reason, line_termination);
     +
     +	fwrite(sb.buf, sb.len, 1, stdout);
     +	strbuf_release(&sb);
    @@ builtin/update-ref.c: int cmd_update_ref(int argc,
      	int delete = 0, no_deref = 0, read_stdin = 0, end_null = 0;
     -	int create_reflog = 0;
     +	int create_reflog = 0, allow_partial = 0;
    ++	unsigned int flags = 0;
     +
      	struct option options[] = {
      		OPT_STRING( 'm', NULL, &msg, N_("reason"), N_("reason of the update")),
    @@ builtin/update-ref.c: int cmd_update_ref(int argc,
      		OPT_BOOL('z', NULL, &end_null, N_("stdin has NUL-terminated arguments")),
      		OPT_BOOL( 0 , "stdin", &read_stdin, N_("read updates from stdin")),
      		OPT_BOOL( 0 , "create-reflog", &create_reflog, N_("create a reflog")),
    -+		OPT_BOOL('0', "allow-partial", &allow_partial, N_("allow partial transactions")),
    ++		OPT_BIT('0', "allow-partial", &flags, N_("allow partial transactions"),
    ++			REF_TRANSACTION_ALLOW_PARTIAL),
      		OPT_END(),
      	};
      
     @@ builtin/update-ref.c: int cmd_update_ref(int argc,
    - 	}
    - 
    - 	if (read_stdin) {
    -+		unsigned int flags = 0;
    -+
    -+		if (allow_partial)
    -+			flags |= REF_TRANSACTION_ALLOW_PARTIAL;
    -+
    - 		if (delete || argc > 0)
      			usage_with_options(git_update_ref_usage, options);
      		if (end_null)
      			line_termination = '\0';
    @@ t/t1400-update-ref.sh: do
     +			echo $head >expect &&
     +			git rev-parse refs/heads/ref2 >actual &&
     +			test_cmp expect actual &&
    -+			test_grep -q "trying to write ref ${SQ}refs/heads/ref2${SQ} with nonexistent object" stdout
    ++			test_grep -q "invalid new value provided" stdout
     +		)
     +	'
     +
    @@ t/t1400-update-ref.sh: do
     +			echo $head >expect &&
     +			git rev-parse refs/heads/ref2 >actual &&
     +			test_cmp expect actual &&
    -+			test_grep -q "trying to write non-commit object $head_tree to branch ${SQ}refs/heads/ref2${SQ}" stdout
    ++			test_grep -q "invalid new value provided" stdout
     +		)
     +	'
     +
    @@ t/t1400-update-ref.sh: do
     +			git rev-parse refs/heads/ref1 >actual &&
     +			test_cmp expect actual &&
     +			test_must_fail git rev-parse refs/heads/ref2 &&
    -+			test_grep -q "unable to resolve reference" stdout
    ++			test_grep -q "reference does not exist" stdout
     +		)
     +	'
     +
    @@ t/t1400-update-ref.sh: do
     +			test_cmp expect actual &&
     +			echo $head >expect &&
     +			test_must_fail git rev-parse refs/heads/ref2 &&
    -+			test_grep -q "reference is missing but expected $head" stdout
    ++			test_grep -q "reference does not exist" stdout
     +		)
     +	'
     +
    @@ t/t1400-update-ref.sh: do
     +			echo $head >expect &&
     +			git rev-parse refs/heads/ref2 >actual &&
     +			test_cmp expect actual &&
    -+			test_grep -q "expected symref with target ${SQ}refs/heads/nonexistent${SQ}: but is a regular ref" stdout
    ++			test_grep -q "expected symref but found regular ref" stdout
     +		)
     +	'
     +
    @@ t/t1400-update-ref.sh: do
     +			echo $head >expect &&
     +			git rev-parse refs/heads/ref2 >actual &&
     +			test_cmp expect actual &&
    -+			test_grep -q "${SQ}refs/heads/ref2${SQ}: is at $head but expected $old_head" stdout
    ++			test_grep -q "incorrect old value provided" stdout
    ++		)
    ++	'
    ++
    ++	# F/D conflicts on the files backend are resolved on an individual
    ++	# update level since refs are stored as files. On the reftable backend
    ++	# this check is batched to optimize for performance, so failures cannot
    ++	# be isolated to a single update.
    ++	test_expect_success REFFILES "stdin $type allow-partial refname conflict" '
    ++		git init repo &&
    ++		test_when_finished "rm -fr repo" &&
    ++		(
    ++			cd repo &&
    ++			test_commit one &&
    ++			old_head=$(git rev-parse HEAD) &&
    ++			test_commit two &&
    ++			head=$(git rev-parse HEAD) &&
    ++			git update-ref refs/heads/ref/foo $head &&
    ++
    ++			format_command $type "update refs/heads/ref/foo" "$old_head" "$head" >stdin &&
    ++			format_command $type "update refs/heads/ref" "$old_head" "" >>stdin &&
    ++			git update-ref $type --stdin --allow-partial <stdin >stdout &&
    ++			echo $old_head >expect &&
    ++			git rev-parse refs/heads/ref/foo >actual &&
    ++			test_cmp expect actual &&
    ++			test_grep -q "refname conflict" stdout
     +		)
     +	'
      done

base-commit: 408c44885d5b61a728dfc1df462490487cb01dae change-id: 20241206-245-partially-atomic-ref-updates-9fe8b080345c

Thanks
- Karthik
Karthik Nayak· Feb 25, 2025, 09:29 UTC · re: Karthik Nayak · lore

In `split_symref_update()`, there were two checks for duplicate refnames:

  - At the start, `string_list_has_string()` ensures the refname is not
    already in `affected_refnames`, preventing duplicates from being
    added.
  - After adding the refname, another check verifies whether the newly
    inserted item has a `util` value.

The second check is unnecessary because the first one guarantees that `string_list_insert()` will never encounter a preexisting entry.

Since `item->util` is only used in this context, remove the assignment and simplify the surrounding code.

Signed-off-by: Karthik Nayak <karthik.188@gmail.com>
---
 refs/files-backend.c | 20 +++-----------------
 1 file changed, 3 insertions(+), 17 deletions(-)
Show changes to refs/files-backend.c +3 −17
diff --git a/refs/files-backend.c b/refs/files-backend.c
index 4e1c50fead..6c7df30738 100644
--- a/refs/files-backend.c
+++ b/refs/files-backend.c
@@ -2382,7 +2382,6 @@ static int split_head_update(struct ref_update *update,
 			     struct string_list *affected_refnames,
 			     struct strbuf *err)
 {
-	struct string_list_item *item;
 	struct ref_update *new_update;
 
 	if ((update->flags & REF_LOG_ONLY) ||
@@ -2421,8 +2420,7 @@ static int split_head_update(struct ref_update *update,
 	 */
 	if (strcmp(new_update->refname, "HEAD"))
 		BUG("%s unexpectedly not 'HEAD'", new_update->refname);
-	item = string_list_insert(affected_refnames, new_update->refname);
-	item->util = new_update;
+	string_list_insert(affected_refnames, new_update->refname);
 
 	return 0;
 }
@@ -2441,7 +2439,6 @@ static int split_symref_update(struct ref_update *update,
 			       struct string_list *affected_refnames,
 			       struct strbuf *err)
 {
-	struct string_list_item *item;
 	struct ref_update *new_update;
 	unsigned int new_flags;
 
@@ -2496,11 +2493,7 @@ static int split_symref_update(struct ref_update *update,
 	 * be valid as long as affected_refnames is in use, and NOT
 	 * referent, which might soon be freed by our caller.
 	 */
-	item = string_list_insert(affected_refnames, new_update->refname);
-	if (item->util)
-		BUG("%s unexpectedly found in affected_refnames",
-		    new_update->refname);
-	item->util = new_update;
+	string_list_insert(affected_refnames, new_update->refname);
 
 	return 0;
 }
@@ -2834,7 +2827,6 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 	 */
 	for (i = 0; i < transaction->nr; i++) {
 		struct ref_update *update = transaction->updates[i];
-		struct string_list_item *item;
 
 		if ((update->flags & REF_IS_PRUNING) &&
 		    !(update->flags & REF_NO_DEREF))
@@ -2843,13 +2835,7 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 		if (update->flags & REF_LOG_ONLY)
 			continue;
 
-		item = string_list_append(&affected_refnames, update->refname);
-		/*
-		 * We store a pointer to update in item->util, but at
-		 * the moment we never use the value of this field
-		 * except to check whether it is non-NULL.
-		 */
-		item->util = update;
+		string_list_append(&affected_refnames, update->refname);
 	}
 	string_list_sort(&affected_refnames);
 	if (ref_update_reject_duplicates(&affected_refnames, err)) {
-- 
2.47.2
Karthik Nayak· Feb 25, 2025, 09:29 UTC · re: Karthik Nayak · lore

[PATCH v2 2/7] refs: move duplicate refname update check to generic layer

Move the tracking of refnames in `affected_refnames` from individual backends into the generic layer in 'refs.c'. This centralizes the duplicate refname detection that was previously handled separately by each backend.

Make some changes to accommodate this move:
  - Add a `string_list` field `refnames` to `ref_transaction` to contain
    all the references in a transaction. This field is updated whenever
    a new update is added via `ref_transaction_add_update`, so manual
    additions in reference backends are dropped.
  - Modify the backends to use this field internally as needed. The
    backends need to check if an update for refname already exists when
    splitting symrefs or adding an update for 'HEAD'.
  - In the reftable backend, within `reftable_be_transaction_prepare()`,
    move the `string_list_has_string()` check above
    `ref_transaction_add_update()`. Since `ref_transaction_add_update()`
    automatically adds the refname to `transaction->refnames`,
    performing the check after will always return true, so we perform
    the check before adding the update.

This helps reduce duplication of functionality between the backends and makes it easier to make changes in a more centralized manner.

Signed-off-by: Karthik Nayak <karthik.188@gmail.com>
---
 refs.c                  | 17 +++++++++++++
 refs/files-backend.c    | 67 +++++++++++--------------------------------------
 refs/packed-backend.c   | 25 +-----------------
 refs/refs-internal.h    |  2 ++
 refs/reftable-backend.c | 54 +++++++++++++--------------------------
 5 files changed, 51 insertions(+), 114 deletions(-)
Show changes to 5 files +51 −114

refs.c, refs/files-backend.c, refs/packed-backend.c, refs/refs-internal.h, refs/reftable-backend.c

diff --git a/refs.c b/refs.c
index 54fd5ce21e..ab69746947 100644
--- a/refs.c
+++ b/refs.c
@@ -1175,6 +1175,7 @@ struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
 	CALLOC_ARRAY(tr, 1);
 	tr->ref_store = refs;
 	tr->flags = flags;
+	string_list_init_dup(&tr->refnames);
 	return tr;
 }
 
@@ -1205,6 +1206,7 @@ void ref_transaction_free(struct ref_transaction *transaction)
 		free((char *)transaction->updates[i]->old_target);
 		free(transaction->updates[i]);
 	}
+	string_list_clear(&transaction->refnames, 0);
 	free(transaction->updates);
 	free(transaction);
 }
@@ -1218,6 +1220,7 @@ struct ref_update *ref_transaction_add_update(
 		const char *committer_info,
 		const char *msg)
 {
+	struct string_list_item *item;
 	struct ref_update *update;
 
 	if (transaction->state != REF_TRANSACTION_OPEN)
@@ -1245,6 +1248,16 @@ struct ref_update *ref_transaction_add_update(
 		update->msg = normalize_reflog_message(msg);
 	}
 
+	/*
+	 * This list is generally used by the backends to avoid duplicates.
+	 * But we do support multiple log updates for a given refname within
+	 * a single transaction.
+	 */
+	if (!(update->flags & REF_LOG_ONLY)) {
+		item = string_list_append(&transaction->refnames, refname);
+		item->util = update;
+	}
+
 	return update;
 }
 
@@ -2405,6 +2418,10 @@ int ref_transaction_prepare(struct ref_transaction *transaction,
 		return -1;
 	}
 
+	string_list_sort(&transaction->refnames);
+	if (ref_update_reject_duplicates(&transaction->refnames, err))
+		return TRANSACTION_GENERIC_ERROR;
+
 	ret = refs->be->transaction_prepare(refs, transaction, err);
 	if (ret)
 		return ret;
diff --git a/refs/files-backend.c b/refs/files-backend.c
index 6c7df30738..85ed85ad87 100644
--- a/refs/files-backend.c
+++ b/refs/files-backend.c
@@ -2378,9 +2378,7 @@ static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_st
  */
 static int split_head_update(struct ref_update *update,
 			     struct ref_transaction *transaction,
-			     const char *head_ref,
-			     struct string_list *affected_refnames,
-			     struct strbuf *err)
+			     const char *head_ref, struct strbuf *err)
 {
 	struct ref_update *new_update;
 
@@ -2398,7 +2396,7 @@ static int split_head_update(struct ref_update *update,
 	 * transaction. This check is O(lg N) in the transaction
 	 * size, but it happens at most once per transaction.
 	 */
-	if (string_list_has_string(affected_refnames, "HEAD")) {
+	if (string_list_has_string(&transaction->refnames, "HEAD")) {
 		/* An entry already existed */
 		strbuf_addf(err,
 			    "multiple updates for 'HEAD' (including one "
@@ -2420,7 +2418,6 @@ static int split_head_update(struct ref_update *update,
 	 */
 	if (strcmp(new_update->refname, "HEAD"))
 		BUG("%s unexpectedly not 'HEAD'", new_update->refname);
-	string_list_insert(affected_refnames, new_update->refname);
 
 	return 0;
 }
@@ -2436,7 +2433,6 @@ static int split_head_update(struct ref_update *update,
 static int split_symref_update(struct ref_update *update,
 			       const char *referent,
 			       struct ref_transaction *transaction,
-			       struct string_list *affected_refnames,
 			       struct strbuf *err)
 {
 	struct ref_update *new_update;
@@ -2448,7 +2444,7 @@ static int split_symref_update(struct ref_update *update,
 	 * size, but it happens at most once per symref in a
 	 * transaction.
 	 */
-	if (string_list_has_string(affected_refnames, referent)) {
+	if (string_list_has_string(&transaction->refnames, referent)) {
 		/* An entry already exists */
 		strbuf_addf(err,
 			    "multiple updates for '%s' (including one "
@@ -2486,15 +2482,6 @@ static int split_symref_update(struct ref_update *update,
 	update->flags |= REF_LOG_ONLY | REF_NO_DEREF;
 	update->flags &= ~REF_HAVE_OLD;
 
-	/*
-	 * Add the referent. This insertion is O(N) in the transaction
-	 * size, but it happens at most once per symref in a
-	 * transaction. Make sure to add new_update->refname, which will
-	 * be valid as long as affected_refnames is in use, and NOT
-	 * referent, which might soon be freed by our caller.
-	 */
-	string_list_insert(affected_refnames, new_update->refname);
-
 	return 0;
 }
 
@@ -2558,7 +2545,6 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 			       struct ref_transaction *transaction,
 			       const char *head_ref,
 			       struct string_list *refnames_to_check,
-			       struct string_list *affected_refnames,
 			       struct strbuf *err)
 {
 	struct strbuf referent = STRBUF_INIT;
@@ -2575,8 +2561,7 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 		update->flags |= REF_DELETING;
 
 	if (head_ref) {
-		ret = split_head_update(update, transaction, head_ref,
-					affected_refnames, err);
+		ret = split_head_update(update, transaction, head_ref, err);
 		if (ret)
 			goto out;
 	}
@@ -2586,9 +2571,8 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 		lock->count++;
 	} else {
 		ret = lock_raw_ref(refs, update->refname, mustexist,
-				   refnames_to_check, affected_refnames,
-				   &lock, &referent,
-				   &update->type, err);
+				   refnames_to_check, &transaction->refnames,
+				   &lock, &referent, &update->type, err);
 		if (ret) {
 			char *reason;
 
@@ -2642,9 +2626,8 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 			 * of processing the split-off update, so we
 			 * don't have to do it here.
 			 */
-			ret = split_symref_update(update,
-						  referent.buf, transaction,
-						  affected_refnames, err);
+			ret = split_symref_update(update, referent.buf,
+						  transaction, err);
 			if (ret)
 				goto out;
 		}
@@ -2799,7 +2782,6 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 			       "ref_transaction_prepare");
 	size_t i;
 	int ret = 0;
-	struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
 	struct string_list refnames_to_check = STRING_LIST_INIT_NODUP;
 	char *head_ref = NULL;
 	int head_type;
@@ -2818,12 +2800,7 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 	transaction->backend_data = backend_data;
 
 	/*
-	 * Fail if a refname appears more than once in the
-	 * transaction. (If we end up splitting up any updates using
-	 * split_symref_update() or split_head_update(), those
-	 * functions will check that the new updates don't have the
-	 * same refname as any existing ones.) Also fail if any of the
-	 * updates use REF_IS_PRUNING without REF_NO_DEREF.
+	 * Fail if any of the updates use REF_IS_PRUNING without REF_NO_DEREF.
 	 */
 	for (i = 0; i < transaction->nr; i++) {
 		struct ref_update *update = transaction->updates[i];
@@ -2831,16 +2808,6 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 		if ((update->flags & REF_IS_PRUNING) &&
 		    !(update->flags & REF_NO_DEREF))
 			BUG("REF_IS_PRUNING set without REF_NO_DEREF");
-
-		if (update->flags & REF_LOG_ONLY)
-			continue;
-
-		string_list_append(&affected_refnames, update->refname);
-	}
-	string_list_sort(&affected_refnames);
-	if (ref_update_reject_duplicates(&affected_refnames, err)) {
-		ret = TRANSACTION_GENERIC_ERROR;
-		goto cleanup;
 	}
 
 	/*
@@ -2882,7 +2849,7 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 
 		ret = lock_ref_for_update(refs, update, transaction,
 					  head_ref, &refnames_to_check,
-					  &affected_refnames, err);
+					  err);
 		if (ret)
 			goto cleanup;
 
@@ -2929,7 +2896,7 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 	 * So instead, we accept the race for now.
 	 */
 	if (refs_verify_refnames_available(refs->packed_ref_store, &refnames_to_check,
-					   &affected_refnames, NULL, 0, err)) {
+					   &transaction->refnames, NULL, 0, err)) {
 		ret = TRANSACTION_NAME_CONFLICT;
 		goto cleanup;
 	}
@@ -2975,7 +2942,6 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 
 cleanup:
 	free(head_ref);
-	string_list_clear(&affected_refnames, 0);
 	string_list_clear(&refnames_to_check, 0);
 
 	if (ret)
@@ -3050,13 +3016,8 @@ static int files_transaction_finish_initial(struct files_ref_store *refs,
 	if (transaction->state != REF_TRANSACTION_PREPARED)
 		BUG("commit called for transaction that is not prepared");
 
-	/* Fail if a refname appears more than once in the transaction: */
-	for (i = 0; i < transaction->nr; i++)
-		if (!(transaction->updates[i]->flags & REF_LOG_ONLY))
-			string_list_append(&affected_refnames,
-					   transaction->updates[i]->refname);
-	string_list_sort(&affected_refnames);
-	if (ref_update_reject_duplicates(&affected_refnames, err)) {
+	string_list_sort(&transaction->refnames);
+	if (ref_update_reject_duplicates(&transaction->refnames, err)) {
 		ret = TRANSACTION_GENERIC_ERROR;
 		goto cleanup;
 	}
@@ -3074,7 +3035,7 @@ static int files_transaction_finish_initial(struct files_ref_store *refs,
 	 * that we are creating already exists.
 	 */
 	if (refs_for_each_rawref(&refs->base, ref_present,
-				 &affected_refnames))
+				 &transaction->refnames))
 		BUG("initial ref transaction called with existing refs");
 
 	packed_transaction = ref_store_transaction_begin(refs->packed_ref_store,
diff --git a/refs/packed-backend.c b/refs/packed-backend.c
index 71a38acfed..3247871574 100644
--- a/refs/packed-backend.c
+++ b/refs/packed-backend.c
@@ -1619,8 +1619,6 @@ int is_packed_transaction_needed(struct ref_store *ref_store,
 struct packed_transaction_backend_data {
 	/* True iff the transaction owns the packed-refs lock. */
 	int own_lock;
-
-	struct string_list updates;
 };
 
 static void packed_transaction_cleanup(struct packed_ref_store *refs,
@@ -1629,8 +1627,6 @@ static void packed_transaction_cleanup(struct packed_ref_store *refs,
 	struct packed_transaction_backend_data *data = transaction->backend_data;
 
 	if (data) {
-		string_list_clear(&data->updates, 0);
-
 		if (is_tempfile_active(refs->tempfile))
 			delete_tempfile(&refs->tempfile);
 
@@ -1655,7 +1651,6 @@ static int packed_transaction_prepare(struct ref_store *ref_store,
 			REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
 			"ref_transaction_prepare");
 	struct packed_transaction_backend_data *data;
-	size_t i;
 	int ret = TRANSACTION_GENERIC_ERROR;
 
 	/*
@@ -1668,34 +1663,16 @@ static int packed_transaction_prepare(struct ref_store *ref_store,
 	 */
 
 	CALLOC_ARRAY(data, 1);
-	string_list_init_nodup(&data->updates);
 
 	transaction->backend_data = data;
 
-	/*
-	 * Stick the updates in a string list by refname so that we
-	 * can sort them:
-	 */
-	for (i = 0; i < transaction->nr; i++) {
-		struct ref_update *update = transaction->updates[i];
-		struct string_list_item *item =
-			string_list_append(&data->updates, update->refname);
-
-		/* Store a pointer to update in item->util: */
-		item->util = update;
-	}
-	string_list_sort(&data->updates);
-
-	if (ref_update_reject_duplicates(&data->updates, err))
-		goto failure;
-
 	if (!is_lock_file_locked(&refs->lock)) {
 		if (packed_refs_lock(ref_store, 0, err))
 			goto failure;
 		data->own_lock = 1;
 	}
 
-	if (write_with_updates(refs, &data->updates, err))
+	if (write_with_updates(refs, &transaction->refnames, err))
 		goto failure;
 
 	transaction->state = REF_TRANSACTION_PREPARED;
diff --git a/refs/refs-internal.h b/refs/refs-internal.h
index cadd9808fd..a6e05eaecd 100644
--- a/refs/refs-internal.h
+++ b/refs/refs-internal.h
@@ -3,6 +3,7 @@
 
 #include "refs.h"
 #include "iterator.h"
+#include "string-list.h"
 
 struct fsck_options;
 struct ref_transaction;
@@ -198,6 +199,7 @@ enum ref_transaction_state {
 struct ref_transaction {
 	struct ref_store *ref_store;
 	struct ref_update **updates;
+	struct string_list refnames;
 	size_t alloc;
 	size_t nr;
 	enum ref_transaction_state state;
diff --git a/refs/reftable-backend.c b/refs/reftable-backend.c
index 441b8c69c1..f616d9aabe 100644
--- a/refs/reftable-backend.c
+++ b/refs/reftable-backend.c
@@ -1076,7 +1076,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 	struct reftable_ref_store *refs =
 		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 affected_refnames = STRING_LIST_INIT_NODUP;
 	struct string_list refnames_to_check = STRING_LIST_INIT_NODUP;
 	struct reftable_transaction_data *tx_data = NULL;
 	struct reftable_backend *be;
@@ -1101,10 +1100,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 						 transaction->updates[i], err);
 		if (ret)
 			goto done;
-
-		if (!(transaction->updates[i]->flags & REF_LOG_ONLY))
-			string_list_append(&affected_refnames,
-					   transaction->updates[i]->refname);
 	}
 
 	/*
@@ -1116,17 +1111,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 		tx_data->args[i].updates_alloc = tx_data->args[i].updates_expected;
 	}
 
-	/*
-	 * Fail if a refname appears more than once in the transaction.
-	 * This code is taken from the files backend and is a good candidate to
-	 * be moved into the generic layer.
-	 */
-	string_list_sort(&affected_refnames);
-	if (ref_update_reject_duplicates(&affected_refnames, err)) {
-		ret = TRANSACTION_GENERIC_ERROR;
-		goto done;
-	}
-
 	/*
 	 * TODO: it's dubious whether we should reload the stack that "HEAD"
 	 * belongs to or not. In theory, it may happen that we only modify
@@ -1194,14 +1178,12 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 		    !(u->flags & REF_LOG_ONLY) &&
 		    !(u->flags & REF_UPDATE_VIA_HEAD) &&
 		    !strcmp(rewritten_ref, head_referent.buf)) {
-			struct ref_update *new_update;
-
 			/*
 			 * First make sure that HEAD is not already in the
 			 * transaction. This check is O(lg N) in the transaction
 			 * size, but it happens at most once per transaction.
 			 */
-			if (string_list_has_string(&affected_refnames, "HEAD")) {
+			if (string_list_has_string(&transaction->refnames, "HEAD")) {
 				/* An entry already existed */
 				strbuf_addf(err,
 					    _("multiple updates for 'HEAD' (including one "
@@ -1211,12 +1193,11 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 				goto done;
 			}
 
-			new_update = ref_transaction_add_update(
-					transaction, "HEAD",
-					u->flags | REF_LOG_ONLY | REF_NO_DEREF,
-					&u->new_oid, &u->old_oid, NULL, NULL, NULL,
-					u->msg);
-			string_list_insert(&affected_refnames, new_update->refname);
+			ref_transaction_add_update(
+				transaction, "HEAD",
+				u->flags | REF_LOG_ONLY | REF_NO_DEREF,
+				&u->new_oid, &u->old_oid, NULL, NULL, NULL,
+				u->msg);
 		}
 
 		ret = reftable_backend_read_ref(be, rewritten_ref,
@@ -1281,6 +1262,15 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 				if (!strcmp(rewritten_ref, "HEAD"))
 					new_flags |= REF_UPDATE_VIA_HEAD;
 
+				if (string_list_has_string(&transaction->refnames, referent.buf)) {
+					strbuf_addf(err,
+						    _("multiple updates for '%s' (including one "
+						    "via symref '%s') are not allowed"),
+						    referent.buf, u->refname);
+					ret = TRANSACTION_NAME_CONFLICT;
+					goto done;
+				}
+
 				/*
 				 * If we are updating a symref (eg. HEAD), we should also
 				 * update the branch that the symref points to.
@@ -1305,16 +1295,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 				 */
 				u->flags |= REF_LOG_ONLY | REF_NO_DEREF;
 				u->flags &= ~REF_HAVE_OLD;
-
-				if (string_list_has_string(&affected_refnames, new_update->refname)) {
-					strbuf_addf(err,
-						    _("multiple updates for '%s' (including one "
-						    "via symref '%s') are not allowed"),
-						    referent.buf, u->refname);
-					ret = TRANSACTION_NAME_CONFLICT;
-					goto done;
-				}
-				string_list_insert(&affected_refnames, new_update->refname);
 			}
 		}
 
@@ -1384,7 +1364,8 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 	}
 
 	string_list_sort(&refnames_to_check);
-	ret = refs_verify_refnames_available(ref_store, &refnames_to_check, &affected_refnames, NULL,
+	ret = refs_verify_refnames_available(ref_store, &refnames_to_check,
+					     &transaction->refnames, NULL,
 					     transaction->flags & REF_TRANSACTION_FLAG_INITIAL,
 					     err);
 	if (ret < 0)
@@ -1402,7 +1383,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 			strbuf_addf(err, _("reftable: transaction prepare: %s"),
 				    reftable_error_str(ret));
 	}
-	string_list_clear(&affected_refnames, 0);
 	strbuf_release(&referent);
 	strbuf_release(&head_referent);
 	string_list_clear(&refnames_to_check, 0);
-- 
2.47.2
Karthik Nayak· Feb 25, 2025, 09:29 UTC · re: Karthik Nayak · lore

[PATCH v2 3/7] refs/files: remove duplicate duplicates check

Within the files reference backend's transaction's 'finish' phase, a verification step is currently performed wherein the refnames list is sorted and examined for multiple updates targeting the same refname.

It has been observed that this verification is redundant, as an identical check is already executed during the transaction's 'prepare' stage. Since the refnames list remains unmodified following the 'prepare' stage, this secondary verification can be safely eliminated.

The duplicate check has been removed accordingly, and the `ref_update_reject_duplicates()` function has been marked as static, as its usage is now confined to 'refs.c'.

Signed-off-by: Karthik Nayak <karthik.188@gmail.com>
---
 refs.c               | 9 +++++++--
 refs/files-backend.c | 6 ------
 refs/refs-internal.h | 8 --------
 3 files changed, 7 insertions(+), 16 deletions(-)
Show changes to 3 files +7 −16

refs.c, refs/files-backend.c, refs/refs-internal.h

diff --git a/refs.c b/refs.c
index ab69746947..69f385f344 100644
--- a/refs.c
+++ b/refs.c
@@ -2303,8 +2303,13 @@ int refs_update_symref_extended(struct ref_store *refs, const char *ref,
 	return ret;
 }
 
-int ref_update_reject_duplicates(struct string_list *refnames,
-				 struct strbuf *err)
+/*
+ * Write an error to `err` and return a nonzero value iff the same
+ * refname appears multiple times in `refnames`. `refnames` must be
+ * sorted on entry to this function.
+ */
+static int ref_update_reject_duplicates(struct string_list *refnames,
+					struct strbuf *err)
 {
 	size_t i, n = refnames->nr;
 
diff --git a/refs/files-backend.c b/refs/files-backend.c
index 85ed85ad87..7c6a0b3478 100644
--- a/refs/files-backend.c
+++ b/refs/files-backend.c
@@ -3016,12 +3016,6 @@ static int files_transaction_finish_initial(struct files_ref_store *refs,
 	if (transaction->state != REF_TRANSACTION_PREPARED)
 		BUG("commit called for transaction that is not prepared");
 
-	string_list_sort(&transaction->refnames);
-	if (ref_update_reject_duplicates(&transaction->refnames, err)) {
-		ret = TRANSACTION_GENERIC_ERROR;
-		goto cleanup;
-	}
-
 	/*
 	 * It's really undefined to call this function in an active
 	 * repository or when there are existing references: we are
diff --git a/refs/refs-internal.h b/refs/refs-internal.h
index a6e05eaecd..4b7fc8f1ab 100644
--- a/refs/refs-internal.h
+++ b/refs/refs-internal.h
@@ -142,14 +142,6 @@ int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
 		      struct object_id *oid, struct strbuf *referent,
 		      unsigned int *type, int *failure_errno);
 
-/*
- * Write an error to `err` and return a nonzero value iff the same
- * refname appears multiple times in `refnames`. `refnames` must be
- * sorted on entry to this function.
- */
-int ref_update_reject_duplicates(struct string_list *refnames,
-				 struct strbuf *err);
-
 /*
  * Add a ref_update with the specified properties to transaction, and
  * return a pointer to the new object. This function does not verify
-- 
2.47.2
Karthik Nayak· Feb 25, 2025, 09:29 UTC · re: Karthik Nayak · lore

[PATCH v2 4/7] refs/reftable: extract code from the transaction preparation

Extract the core logic for preparing individual reference updates from `reftable_be_transaction_prepare()` into `prepare_single_update()`. This dedicated function now handles all validation and preparation steps for each reference update in the transaction, including object ID verification, HEAD reference handling, and symref processing.

The refactoring consolidates all reference update validation into a single logical block, which improves code maintainability and readability. More importantly, this restructuring lays the groundwork for implementing partial transaction support in the reftable backend, which will be introduced in the following commit.

No functional changes are included in this commit - it is purely a code reorganization to support future enhancements.

Signed-off-by: Karthik Nayak <karthik.188@gmail.com>
---
 refs/reftable-backend.c | 463 +++++++++++++++++++++++++-----------------------
 1 file changed, 237 insertions(+), 226 deletions(-)
Show changes to refs/reftable-backend.c +237 −226
diff --git a/refs/reftable-backend.c b/refs/reftable-backend.c
index f616d9aabe..2c1e2995de 100644
--- a/refs/reftable-backend.c
+++ b/refs/reftable-backend.c
@@ -1069,6 +1069,239 @@ static int queue_transaction_update(struct reftable_ref_store *refs,
 	return 0;
 }
 
+static int prepare_single_update(struct reftable_ref_store *refs,
+				 struct reftable_transaction_data *tx_data,
+				 struct ref_transaction *transaction,
+				 struct reftable_backend *be,
+				 struct ref_update *u,
+				 struct string_list *refnames_to_check,
+				 unsigned int head_type,
+				 struct strbuf *head_referent,
+				 struct strbuf *referent,
+				 struct strbuf *err)
+{
+	struct object_id current_oid = {0};
+	const char *rewritten_ref;
+	int ret = 0;
+
+	/*
+	 * There is no need to reload the respective backends here as
+	 * we have already reloaded them when preparing the transaction
+	 * update. And given that the stacks have been locked there
+	 * shouldn't have been any concurrent modifications of the
+	 * stack.
+	 */
+	ret = backend_for(&be, refs, u->refname, &rewritten_ref, 0);
+	if (ret)
+		return ret;
+
+	/* Verify that the new object ID is valid. */
+	if ((u->flags & REF_HAVE_NEW) && !is_null_oid(&u->new_oid) &&
+	    !(u->flags & REF_SKIP_OID_VERIFICATION) &&
+	    !(u->flags & REF_LOG_ONLY)) {
+		struct object *o = parse_object(refs->base.repo, &u->new_oid);
+		if (!o) {
+			strbuf_addf(err,
+				    _("trying to write ref '%s' with nonexistent object %s"),
+				    u->refname, oid_to_hex(&u->new_oid));
+			return -1;
+		}
+
+		if (o->type != OBJ_COMMIT && is_branch(u->refname)) {
+			strbuf_addf(err, _("trying to write non-commit object %s to branch '%s'"),
+				    oid_to_hex(&u->new_oid), u->refname);
+			return -1;
+		}
+	}
+
+	/*
+	 * When we update the reference that HEAD points to we enqueue
+	 * a second log-only update for HEAD so that its reflog is
+	 * updated accordingly.
+	 */
+	if (head_type == REF_ISSYMREF &&
+	    !(u->flags & REF_LOG_ONLY) &&
+	    !(u->flags & REF_UPDATE_VIA_HEAD) &&
+	    !strcmp(rewritten_ref, head_referent->buf)) {
+		/*
+		 * First make sure that HEAD is not already in the
+		 * transaction. This check is O(lg N) in the transaction
+		 * size, but it happens at most once per transaction.
+		 */
+		if (string_list_has_string(&transaction->refnames, "HEAD")) {
+			/* An entry already existed */
+			strbuf_addf(err,
+				    _("multiple updates for 'HEAD' (including one "
+				      "via its referent '%s') are not allowed"),
+				    u->refname);
+			return TRANSACTION_NAME_CONFLICT;
+		}
+
+		ref_transaction_add_update(
+			transaction, "HEAD",
+			u->flags | REF_LOG_ONLY | REF_NO_DEREF,
+			&u->new_oid, &u->old_oid, NULL, NULL, NULL,
+			u->msg);
+	}
+
+	ret = reftable_backend_read_ref(be, rewritten_ref,
+					&current_oid, referent, &u->type);
+	if (ret < 0)
+		return ret;
+	if (ret > 0 && !ref_update_expects_existing_old_ref(u)) {
+		/*
+		 * The reference does not exist, and we either have no
+		 * old object ID or expect the reference to not exist.
+		 * We can thus skip below safety checks as well as the
+		 * symref splitting. But we do want to verify that
+		 * there is no conflicting reference here so that we
+		 * can output a proper error message instead of failing
+		 * at a later point.
+		 */
+		string_list_append(refnames_to_check, u->refname);
+
+		/*
+		 * There is no need to write the reference deletion
+		 * when the reference in question doesn't exist.
+		 */
+		if ((u->flags & REF_HAVE_NEW) && !ref_update_has_null_new_value(u)) {
+			ret = queue_transaction_update(refs, tx_data, u,
+						       &current_oid, err);
+			if (ret)
+				return ret;
+		}
+
+		return 0;
+	}
+	if (ret > 0) {
+		/* The reference does not exist, but we expected it to. */
+		strbuf_addf(err, _("cannot lock ref '%s': "
+
+
+				   "unable to resolve reference '%s'"),
+			    ref_update_original_update_refname(u), u->refname);
+		return -1;
+	}
+
+	if (u->type & REF_ISSYMREF) {
+		/*
+		 * The reftable stack is locked at this point already,
+		 * so it is safe to call `refs_resolve_ref_unsafe()`
+		 * here without causing races.
+		 */
+		const char *resolved = refs_resolve_ref_unsafe(&refs->base, u->refname, 0,
+							       &current_oid, NULL);
+
+		if (u->flags & REF_NO_DEREF) {
+			if (u->flags & REF_HAVE_OLD && !resolved) {
+				strbuf_addf(err, _("cannot lock ref '%s': "
+						   "error reading reference"), u->refname);
+				return -1;
+			}
+		} else {
+			struct ref_update *new_update;
+			int new_flags;
+
+			new_flags = u->flags;
+			if (!strcmp(rewritten_ref, "HEAD"))
+				new_flags |= REF_UPDATE_VIA_HEAD;
+
+			if (string_list_has_string(&transaction->refnames, referent->buf)) {
+				strbuf_addf(err,
+					    _("multiple updates for '%s' (including one "
+					      "via symref '%s') are not allowed"),
+					    referent->buf, u->refname);
+				return TRANSACTION_NAME_CONFLICT;
+			}
+
+			/*
+			 * If we are updating a symref (eg. HEAD), we should also
+			 * update the branch that the symref points to.
+			 *
+			 * This is generic functionality, and would be better
+			 * done in refs.c, but the current implementation is
+			 * intertwined with the locking in files-backend.c.
+			 */
+			new_update = ref_transaction_add_update(
+				transaction, referent->buf, new_flags,
+				u->new_target ? NULL : &u->new_oid,
+				u->old_target ? NULL : &u->old_oid,
+				u->new_target, u->old_target,
+				u->committer_info, u->msg);
+
+			new_update->parent_update = u;
+
+			/*
+			 * Change the symbolic ref update to log only. Also, it
+			 * doesn't need to check its old OID value, as that will be
+			 * done when new_update is processed.
+			 */
+			u->flags |= REF_LOG_ONLY | REF_NO_DEREF;
+			u->flags &= ~REF_HAVE_OLD;
+		}
+	}
+
+	/*
+	 * Verify that the old object matches our expectations. Note
+	 * that the error messages here do not make a lot of sense in
+	 * the context of the reftable backend as we never lock
+	 * individual refs. But the error messages match what the files
+	 * backend returns, which keeps our tests happy.
+	 */
+	if (u->old_target) {
+		if (!(u->type & REF_ISSYMREF)) {
+			strbuf_addf(err, _("cannot lock ref '%s': "
+					   "expected symref with target '%s': "
+					   "but is a regular ref"),
+				    ref_update_original_update_refname(u),
+				    u->old_target);
+			return -1;
+		}
+
+		if (ref_update_check_old_target(referent->buf, u, err)) {
+			return -1;
+		}
+	} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
+		if (is_null_oid(&u->old_oid)) {
+			strbuf_addf(err, _("cannot lock ref '%s': "
+					   "reference already exists"),
+				    ref_update_original_update_refname(u));
+			return TRANSACTION_CREATE_EXISTS;
+		}
+		else if (is_null_oid(&current_oid))
+			strbuf_addf(err, _("cannot lock ref '%s': "
+					   "reference is missing but expected %s"),
+				    ref_update_original_update_refname(u),
+				    oid_to_hex(&u->old_oid));
+		else
+			strbuf_addf(err, _("cannot lock ref '%s': "
+					   "is at %s but expected %s"),
+				    ref_update_original_update_refname(u),
+				    oid_to_hex(&current_oid),
+				    oid_to_hex(&u->old_oid));
+		return TRANSACTION_NAME_CONFLICT;
+	}
+
+	/*
+	 * If all of the following conditions are true:
+	 *
+	 *   - We're not about to write a symref.
+	 *   - We're not about to write a log-only entry.
+	 *   - Old and new object ID are different.
+	 *
+	 * Then we're essentially doing a no-op update that can be
+	 * skipped. This is not only for the sake of efficiency, but
+	 * also skips writing unneeded reflog entries.
+	 */
+	if ((u->type & REF_ISSYMREF) ||
+	    (u->flags & REF_LOG_ONLY) ||
+	    (u->flags & REF_HAVE_NEW && !oideq(&current_oid, &u->new_oid)))
+		return queue_transaction_update(refs, tx_data, u,
+					       &current_oid, err);
+
+	return 0;
+}
+
 static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 					   struct ref_transaction *transaction,
 					   struct strbuf *err)
@@ -1133,234 +1366,12 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 	ret = 0;
 
 	for (i = 0; i < transaction->nr; i++) {
-		struct ref_update *u = transaction->updates[i];
-		struct object_id current_oid = {0};
-		const char *rewritten_ref;
-
-		/*
-		 * There is no need to reload the respective backends here as
-		 * we have already reloaded them when preparing the transaction
-		 * update. And given that the stacks have been locked there
-		 * shouldn't have been any concurrent modifications of the
-		 * stack.
-		 */
-		ret = backend_for(&be, refs, u->refname, &rewritten_ref, 0);
+		ret = prepare_single_update(refs, tx_data, transaction, be,
+					    transaction->updates[i],
+					    &refnames_to_check, head_type,
+					    &head_referent, &referent, err);
 		if (ret)
 			goto done;
-
-		/* Verify that the new object ID is valid. */
-		if ((u->flags & REF_HAVE_NEW) && !is_null_oid(&u->new_oid) &&
-		    !(u->flags & REF_SKIP_OID_VERIFICATION) &&
-		    !(u->flags & REF_LOG_ONLY)) {
-			struct object *o = parse_object(refs->base.repo, &u->new_oid);
-			if (!o) {
-				strbuf_addf(err,
-					    _("trying to write ref '%s' with nonexistent object %s"),
-					    u->refname, oid_to_hex(&u->new_oid));
-				ret = -1;
-				goto done;
-			}
-
-			if (o->type != OBJ_COMMIT && is_branch(u->refname)) {
-				strbuf_addf(err, _("trying to write non-commit object %s to branch '%s'"),
-					    oid_to_hex(&u->new_oid), u->refname);
-				ret = -1;
-				goto done;
-			}
-		}
-
-		/*
-		 * When we update the reference that HEAD points to we enqueue
-		 * a second log-only update for HEAD so that its reflog is
-		 * updated accordingly.
-		 */
-		if (head_type == REF_ISSYMREF &&
-		    !(u->flags & REF_LOG_ONLY) &&
-		    !(u->flags & REF_UPDATE_VIA_HEAD) &&
-		    !strcmp(rewritten_ref, head_referent.buf)) {
-			/*
-			 * First make sure that HEAD is not already in the
-			 * transaction. This check is O(lg N) in the transaction
-			 * size, but it happens at most once per transaction.
-			 */
-			if (string_list_has_string(&transaction->refnames, "HEAD")) {
-				/* An entry already existed */
-				strbuf_addf(err,
-					    _("multiple updates for 'HEAD' (including one "
-					    "via its referent '%s') are not allowed"),
-					    u->refname);
-				ret = TRANSACTION_NAME_CONFLICT;
-				goto done;
-			}
-
-			ref_transaction_add_update(
-				transaction, "HEAD",
-				u->flags | REF_LOG_ONLY | REF_NO_DEREF,
-				&u->new_oid, &u->old_oid, NULL, NULL, NULL,
-				u->msg);
-		}
-
-		ret = reftable_backend_read_ref(be, rewritten_ref,
-						&current_oid, &referent, &u->type);
-		if (ret < 0)
-			goto done;
-		if (ret > 0 && !ref_update_expects_existing_old_ref(u)) {
-			/*
-			 * The reference does not exist, and we either have no
-			 * old object ID or expect the reference to not exist.
-			 * We can thus skip below safety checks as well as the
-			 * symref splitting. But we do want to verify that
-			 * there is no conflicting reference here so that we
-			 * can output a proper error message instead of failing
-			 * at a later point.
-			 */
-			string_list_append(&refnames_to_check, u->refname);
-
-			/*
-			 * There is no need to write the reference deletion
-			 * when the reference in question doesn't exist.
-			 */
-			 if ((u->flags & REF_HAVE_NEW) && !ref_update_has_null_new_value(u)) {
-				 ret = queue_transaction_update(refs, tx_data, u,
-								&current_oid, err);
-				 if (ret)
-					 goto done;
-			 }
-
-			continue;
-		}
-		if (ret > 0) {
-			/* The reference does not exist, but we expected it to. */
-			strbuf_addf(err, _("cannot lock ref '%s': "
-				    "unable to resolve reference '%s'"),
-				    ref_update_original_update_refname(u), u->refname);
-			ret = -1;
-			goto done;
-		}
-
-		if (u->type & REF_ISSYMREF) {
-			/*
-			 * The reftable stack is locked at this point already,
-			 * so it is safe to call `refs_resolve_ref_unsafe()`
-			 * here without causing races.
-			 */
-			const char *resolved = refs_resolve_ref_unsafe(&refs->base, u->refname, 0,
-								       &current_oid, NULL);
-
-			if (u->flags & REF_NO_DEREF) {
-				if (u->flags & REF_HAVE_OLD && !resolved) {
-					strbuf_addf(err, _("cannot lock ref '%s': "
-						    "error reading reference"), u->refname);
-					ret = -1;
-					goto done;
-				}
-			} else {
-				struct ref_update *new_update;
-				int new_flags;
-
-				new_flags = u->flags;
-				if (!strcmp(rewritten_ref, "HEAD"))
-					new_flags |= REF_UPDATE_VIA_HEAD;
-
-				if (string_list_has_string(&transaction->refnames, referent.buf)) {
-					strbuf_addf(err,
-						    _("multiple updates for '%s' (including one "
-						    "via symref '%s') are not allowed"),
-						    referent.buf, u->refname);
-					ret = TRANSACTION_NAME_CONFLICT;
-					goto done;
-				}
-
-				/*
-				 * If we are updating a symref (eg. HEAD), we should also
-				 * update the branch that the symref points to.
-				 *
-				 * This is generic functionality, and would be better
-				 * done in refs.c, but the current implementation is
-				 * intertwined with the locking in files-backend.c.
-				 */
-				new_update = ref_transaction_add_update(
-					transaction, referent.buf, new_flags,
-					u->new_target ? NULL : &u->new_oid,
-					u->old_target ? NULL : &u->old_oid,
-					u->new_target, u->old_target,
-					u->committer_info, u->msg);
-
-				new_update->parent_update = u;
-
-				/*
-				 * Change the symbolic ref update to log only. Also, it
-				 * doesn't need to check its old OID value, as that will be
-				 * done when new_update is processed.
-				 */
-				u->flags |= REF_LOG_ONLY | REF_NO_DEREF;
-				u->flags &= ~REF_HAVE_OLD;
-			}
-		}
-
-		/*
-		 * Verify that the old object matches our expectations. Note
-		 * that the error messages here do not make a lot of sense in
-		 * the context of the reftable backend as we never lock
-		 * individual refs. But the error messages match what the files
-		 * backend returns, which keeps our tests happy.
-		 */
-		if (u->old_target) {
-			if (!(u->type & REF_ISSYMREF)) {
-				strbuf_addf(err, _("cannot lock ref '%s': "
-					   "expected symref with target '%s': "
-					   "but is a regular ref"),
-					    ref_update_original_update_refname(u),
-					    u->old_target);
-				ret = -1;
-				goto done;
-			}
-
-			if (ref_update_check_old_target(referent.buf, u, err)) {
-				ret = -1;
-				goto done;
-			}
-		} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
-			ret = TRANSACTION_NAME_CONFLICT;
-			if (is_null_oid(&u->old_oid)) {
-				strbuf_addf(err, _("cannot lock ref '%s': "
-						   "reference already exists"),
-					    ref_update_original_update_refname(u));
-				ret = TRANSACTION_CREATE_EXISTS;
-			}
-			else if (is_null_oid(&current_oid))
-				strbuf_addf(err, _("cannot lock ref '%s': "
-						   "reference is missing but expected %s"),
-					    ref_update_original_update_refname(u),
-					    oid_to_hex(&u->old_oid));
-			else
-				strbuf_addf(err, _("cannot lock ref '%s': "
-						   "is at %s but expected %s"),
-					    ref_update_original_update_refname(u),
-					    oid_to_hex(&current_oid),
-					    oid_to_hex(&u->old_oid));
-			goto done;
-		}
-
-		/*
-		 * If all of the following conditions are true:
-		 *
-		 *   - We're not about to write a symref.
-		 *   - We're not about to write a log-only entry.
-		 *   - Old and new object ID are different.
-		 *
-		 * Then we're essentially doing a no-op update that can be
-		 * skipped. This is not only for the sake of efficiency, but
-		 * also skips writing unneeded reflog entries.
-		 */
-		if ((u->type & REF_ISSYMREF) ||
-		    (u->flags & REF_LOG_ONLY) ||
-		    (u->flags & REF_HAVE_NEW && !oideq(&current_oid, &u->new_oid))) {
-			ret = queue_transaction_update(refs, tx_data, u,
-						       &current_oid, err);
-			if (ret)
-				goto done;
-		}
 	}
 
 	string_list_sort(&refnames_to_check);
-- 
2.47.2
Karthik Nayak· Feb 25, 2025, 09:29 UTC · re: Karthik Nayak · lore

[PATCH v2 6/7] refs: implement partial reference transaction support

Git's reference transactions are all-or-nothing: either all updates succeed, or none do. While this atomic behavior is generally desirable, it can be suboptimal especially when using the reftable backend, where batching multiple reference updates into a single transaction is more efficient than performing them sequentially.

Introduce partial transaction support with a new flag, 'REF_TRANSACTION_ALLOW_PARTIAL'. When enabled, this flag allows individual reference updates that would typically cause the entire transaction to fail due to non-system-related errors to be marked as rejected while permitting other updates to proceed. Non-system-related errors include issues caused by user-provided input values, whereas system-related errors, such as I/O failures or memory issues, continue to result in a full transaction failure. This approach enhances flexibility while preserving transactional integrity where necessary.

The implementation introduces several key components:
  - Add 'rejection_err' field to struct `ref_update` to track failed
    updates with failure reason.
  - Modify reference backends (files, packed, reftable) to handle
    partial transactions by using `ref_transaction_set_rejected()`
    instead of failing the entire transaction when
    `REF_TRANSACTION_ALLOW_PARTIAL` is set.
  - Add `ref_transaction_for_each_rejected_update()` to let callers
    examine which updates were rejected and why.

This foundational change enables partial transaction support throughout the reference subsystem. The next commit will expose this capability to users by adding a `--allow-partial` flag to 'git-update-ref(1)', providing both a user-facing feature and a testable implementation.

Signed-off-by: Karthik Nayak <karthik.188@gmail.com>
---
 refs.c                  | 31 +++++++++++++++++++++++++++++++
 refs.h                  | 22 ++++++++++++++++++++++
 refs/files-backend.c    | 12 +++++++++++-
 refs/packed-backend.c   | 30 ++++++++++++++++++++++++++++--
 refs/refs-internal.h    | 13 +++++++++++++
 refs/reftable-backend.c | 12 +++++++++++-
 6 files changed, 116 insertions(+), 4 deletions(-)
Show changes to 6 files +116 −4

refs.c, refs.h, refs/files-backend.c, refs/packed-backend.c, refs/refs-internal.h, refs/reftable-backend.c

diff --git a/refs.c b/refs.c
index f989a46a5a..243c09c368 100644
--- a/refs.c
+++ b/refs.c
@@ -1211,6 +1211,15 @@ void ref_transaction_free(struct ref_transaction *transaction)
 	free(transaction);
 }
 
+void ref_transaction_set_rejected(struct ref_transaction *transaction,
+				  size_t update_idx,
+				  enum transaction_error err)
+{
+	if (update_idx >= transaction->nr)
+		BUG("trying to set rejection on invalid update index");
+	transaction->updates[update_idx]->rejection_err = err;
+}
+
 struct ref_update *ref_transaction_add_update(
 		struct ref_transaction *transaction,
 		const char *refname, unsigned int flags,
@@ -1236,6 +1245,7 @@ struct ref_update *ref_transaction_add_update(
 	transaction->updates[transaction->nr++] = update;
 
 	update->flags = flags;
+	update->rejection_err = TRANSACTION_OK;
 
 	update->new_target = xstrdup_or_null(new_target);
 	update->old_target = xstrdup_or_null(old_target);
@@ -2726,6 +2736,27 @@ void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
 	}
 }
 
+void ref_transaction_for_each_rejected_update(struct ref_transaction *transaction,
+					      ref_transaction_for_each_rejected_update_fn cb,
+					      void *cb_data)
+{
+	if (!(transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL))
+		return;
+
+	for (size_t i = 0; i < transaction->nr; i++) {
+		struct ref_update *update = transaction->updates[i];
+
+		if (!update->rejection_err)
+			continue;
+
+		cb(update->refname,
+		   (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
+		   (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
+		   update->old_target, update->new_target,
+		   update->rejection_err, cb_data);
+	}
+}
+
 int refs_delete_refs(struct ref_store *refs, const char *logmsg,
 		     struct string_list *refnames, unsigned int flags)
 {
diff --git a/refs.h b/refs.h
index 8e9ead174c..e4a6a8218f 100644
--- a/refs.h
+++ b/refs.h
@@ -675,6 +675,13 @@ enum ref_transaction_flag {
 	 * either be absent or null_oid.
 	 */
 	REF_TRANSACTION_FLAG_INITIAL = (1 << 0),
+
+	/*
+	 * The transaction mechanism by default fails all updates if any conflict
+	 * is detected. This flag allows transactions to partially apply updates
+	 * while rejecting updates which do not match the expected state.
+	 */
+	REF_TRANSACTION_ALLOW_PARTIAL = (1 << 1),
 };
 
 /*
@@ -905,6 +912,21 @@ void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
 					    ref_transaction_for_each_queued_update_fn cb,
 					    void *cb_data);
 
+/*
+ * Execute the given callback function for each of the reference updates which
+ * have been rejected in the given transaction.
+ */
+typedef void ref_transaction_for_each_rejected_update_fn(const char *refname,
+							 const struct object_id *old_oid,
+							 const struct object_id *new_oid,
+							 const char *old_target,
+							 const char *new_target,
+							 enum transaction_error err,
+							 void *cb_data);
+void ref_transaction_for_each_rejected_update(struct ref_transaction *transaction,
+					      ref_transaction_for_each_rejected_update_fn cb,
+					      void *cb_data);
+
 /*
  * Free `*transaction` and all associated data.
  */
diff --git a/refs/files-backend.c b/refs/files-backend.c
index 3b0adf8bb2..d0a53c9ace 100644
--- a/refs/files-backend.c
+++ b/refs/files-backend.c
@@ -2851,8 +2851,18 @@ static int files_transaction_prepare(struct ref_store *ref_store,
 		ret = lock_ref_for_update(refs, update, transaction,
 					  head_ref, &refnames_to_check,
 					  err);
-		if (ret)
+		if (ret) {
+			if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL &&
+			    ret != TRANSACTION_GENERIC_ERROR) {
+				ref_transaction_set_rejected(transaction, i, ret);
+
+				strbuf_setlen(err, 0);
+				ret = TRANSACTION_OK;
+
+				continue;
+			}
 			goto cleanup;
+		}
 
 		if (update->flags & REF_DELETING &&
 		    !(update->flags & REF_LOG_ONLY) &&
diff --git a/refs/packed-backend.c b/refs/packed-backend.c
index 75e1ebf67d..0857204213 100644
--- a/refs/packed-backend.c
+++ b/refs/packed-backend.c
@@ -1324,10 +1324,11 @@ static int packed_ref_store_remove_on_disk(struct ref_store *ref_store,
  * remain locked when it is done.
  */
 static enum transaction_error write_with_updates(struct packed_ref_store *refs,
-						 struct string_list *updates,
+						 struct ref_transaction *transaction,
 						 struct strbuf *err)
 {
 	enum transaction_error ret = TRANSACTION_GENERIC_ERROR;
+	struct string_list *updates = &transaction->refnames;
 	struct ref_iterator *iter = NULL;
 	size_t i;
 	int ok;
@@ -1408,6 +1409,14 @@ static enum transaction_error write_with_updates(struct packed_ref_store *refs,
 						    "reference already exists",
 						    update->refname);
 					ret = TRANSACTION_CREATE_EXISTS;
+
+					if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL) {
+						ref_transaction_set_rejected(transaction, i, ret);
+						strbuf_setlen(err, 0);
+						ret = 0;
+						continue;
+					}
+
 					goto error;
 				} else if (!oideq(&update->old_oid, iter->oid)) {
 					strbuf_addf(err, "cannot update ref '%s': "
@@ -1416,6 +1425,14 @@ static enum transaction_error write_with_updates(struct packed_ref_store *refs,
 						    oid_to_hex(iter->oid),
 						    oid_to_hex(&update->old_oid));
 					ret = TRANSACTION_INCORRECT_OLD_VALUE;
+
+					if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL) {
+						ref_transaction_set_rejected(transaction, i, ret);
+						strbuf_setlen(err, 0);
+						ret = 0;
+						continue;
+					}
+
 					goto error;
 				}
 			}
@@ -1453,6 +1470,14 @@ static enum transaction_error write_with_updates(struct packed_ref_store *refs,
 					    update->refname,
 					    oid_to_hex(&update->old_oid));
 				return TRANSACTION_NONEXISTENT_REF;
+
+				if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL) {
+					ref_transaction_set_rejected(transaction, i, ret);
+					strbuf_setlen(err, 0);
+					ret = 0;
+					continue;
+				}
+
 				goto error;
 			}
 		}
@@ -1518,6 +1543,7 @@ static enum transaction_error write_with_updates(struct packed_ref_store *refs,
 write_error:
 	strbuf_addf(err, "error writing to %s: %s",
 		    get_tempfile_path(refs->tempfile), strerror(errno));
+	ret = TRANSACTION_GENERIC_ERROR;
 
 error:
 	ref_iterator_free(iter);
@@ -1676,7 +1702,7 @@ static int packed_transaction_prepare(struct ref_store *ref_store,
 		data->own_lock = 1;
 	}
 
-	ret = write_with_updates(refs, &transaction->refnames, err);
+	ret = write_with_updates(refs, transaction, err);
 	if (ret)
 		goto failure;
 
diff --git a/refs/refs-internal.h b/refs/refs-internal.h
index c97045fbed..7196f2d880 100644
--- a/refs/refs-internal.h
+++ b/refs/refs-internal.h
@@ -123,6 +123,11 @@ struct ref_update {
 	 */
 	uint64_t index;
 
+	/*
+	 * Used in partial transactions to mark if a given update was rejected.
+	 */
+	enum transaction_error rejection_err;
+
 	/*
 	 * If this ref_update was split off of a symref update via
 	 * split_symref_update(), then this member points at that
@@ -142,6 +147,14 @@ int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
 		      struct object_id *oid, struct strbuf *referent,
 		      unsigned int *type, int *failure_errno);
 
+/*
+ * Mark a given update as rejected with a given reason. To be used in conjuction
+ * with the `REF_TRANSACTION_ALLOW_PARTIAL` flag to allow partial transactions.
+ */
+void ref_transaction_set_rejected(struct ref_transaction *transaction,
+				  size_t update_idx,
+				  enum transaction_error err);
+
 /*
  * Add a ref_update with the specified properties to transaction, and
  * return a pointer to the new object. This function does not verify
diff --git a/refs/reftable-backend.c b/refs/reftable-backend.c
index e1fd9c2de2..83cf8d582b 100644
--- a/refs/reftable-backend.c
+++ b/refs/reftable-backend.c
@@ -1374,8 +1374,18 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 					    transaction->updates[i],
 					    &refnames_to_check, head_type,
 					    &head_referent, &referent, err);
-		if (ret)
+		if (ret) {
+			if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL &&
+			    ret != TRANSACTION_GENERIC_ERROR) {
+				ref_transaction_set_rejected(transaction, i, ret);
+
+				strbuf_setlen(err, 0);
+				ret = TRANSACTION_OK;
+
+				continue;
+			}
 			goto done;
+		}
 	}
 
 	string_list_sort(&refnames_to_check);
-- 
2.47.2
Patrick Steinhardt· Feb 25, 2025, 11:07 UTC · re: Karthik Nayak · lore

Re: [PATCH v2 6/7] refs: implement partial reference transaction support

On Tue, Feb 25, 2025 at 10:29:09AM +0100, Karthik Nayak wrote:
Show 20 quoted lines
> diff --git a/refs.c b/refs.c
> index f989a46a5a..243c09c368 100644
> --- a/refs.c
> +++ b/refs.c
> @@ -2726,6 +2736,27 @@ void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
>  	}
>  }
>  
> +void ref_transaction_for_each_rejected_update(struct ref_transaction *transaction,
> +					      ref_transaction_for_each_rejected_update_fn cb,
> +					      void *cb_data)
> +{
> +	if (!(transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL))
> +		return;
> +
> +	for (size_t i = 0; i < transaction->nr; i++) {
> +		struct ref_update *update = transaction->updates[i];
> +
> +		if (!update->rejection_err)
> +			continue;

This kind of proves my point that `TRANSACTION_OK` is pointless and leads to a mixture of using and not using the enum :)

Show 11 quoted lines
> diff --git a/refs/files-backend.c b/refs/files-backend.c
> index 3b0adf8bb2..d0a53c9ace 100644
> --- a/refs/files-backend.c
> +++ b/refs/files-backend.c
> @@ -2851,8 +2851,18 @@ static int files_transaction_prepare(struct ref_store *ref_store,
>  		ret = lock_ref_for_update(refs, update, transaction,
>  					  head_ref, &refnames_to_check,
>  					  err);
> -		if (ret)
> +		if (ret) {
> +			if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL &&

Hm. If the error values were defined as a bitfield we could refactor this to not be a flag, but have a `transaction->accepted_rejections` instead that allows the caller to ask for only a subset of rejections to be accepted.

I'm not quite sure whether it is a good idea, but the logic to handle all of that could be self-contained in `ref_transaction_set_rejected()`: if it returned an error code itself, it would swallow any errors in case the transaction allows a given error, and bubble up the error again in case the error is not allowed. The function could use a rename in that case though, e.g. `ref_transaction_maybe_set_rejected()`.

Patrick
Karthik Nayak· Mar 3, 2025, 20:17 UTC · re: Patrick Steinhardt · lore

Re: [PATCH v2 6/7] refs: implement partial reference transaction support

Patrick Steinhardt <ps@pks.im> writes:
Show 42 quoted lines
> On Tue, Feb 25, 2025 at 10:29:09AM +0100, Karthik Nayak wrote:
>> diff --git a/refs.c b/refs.c
>> index f989a46a5a..243c09c368 100644
>> --- a/refs.c
>> +++ b/refs.c
>> @@ -2726,6 +2736,27 @@ void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
>>  	}
>>  }
>>
>> +void ref_transaction_for_each_rejected_update(struct ref_transaction *transaction,
>> +					      ref_transaction_for_each_rejected_update_fn cb,
>> +					      void *cb_data)
>> +{
>> +	if (!(transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL))
>> +		return;
>> +
>> +	for (size_t i = 0; i < transaction->nr; i++) {
>> +		struct ref_update *update = transaction->updates[i];
>> +
>> +		if (!update->rejection_err)
>> +			continue;
>
> This kind of proves my point that `TRANSACTION_OK` is pointless and
> leads to a mixture of using and not using the enum :)
>
>> diff --git a/refs/files-backend.c b/refs/files-backend.c
>> index 3b0adf8bb2..d0a53c9ace 100644
>> --- a/refs/files-backend.c
>> +++ b/refs/files-backend.c
>> @@ -2851,8 +2851,18 @@ static int files_transaction_prepare(struct ref_store *ref_store,
>>  		ret = lock_ref_for_update(refs, update, transaction,
>>  					  head_ref, &refnames_to_check,
>>  					  err);
>> -		if (ret)
>> +		if (ret) {
>> +			if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL &&
>
> Hm. If the error values were defined as a bitfield we could refactor
> this to not be a flag, but have a `transaction->accepted_rejections`
> instead that allows the caller to ask for only a subset of rejections to
> be accepted.
>

I did consider making them bitfield and even tried playing with that idea. There are a bunch of side affects of doing that in other subsystems which check call use the reference API and expect '< 0' errors.

Show 8 quoted lines
> I'm not quite sure whether it is a good idea, but the logic to handle
> all of that could be self-contained in `ref_transaction_set_rejected()`:
> if it returned an error code itself, it would swallow any errors in case
> the transaction allows a given error, and bubble up the error again in
> case the error is not allowed. The function could use a rename in that
> case though, e.g. `ref_transaction_maybe_set_rejected()`.
>
> Patrick

I think this is great idea, it does cleanup a bunch of the code. I will add this in the next version with the rename. Thanks!

Phillip Wood· Feb 25, 2025, 14:57 UTC · re: Karthik Nayak · lore

Re: [PATCH v2 6/7] refs: implement partial reference transaction support

Hi Karthik
On 25/02/2025 09:29, Karthik Nayak wrote:
Show 28 quoted lines
> Git's reference transactions are all-or-nothing: either all updates
> succeed, or none do. While this atomic behavior is generally desirable,
> it can be suboptimal especially when using the reftable backend, where
> batching multiple reference updates into a single transaction is more
> efficient than performing them sequentially.
> 
> Introduce partial transaction support with a new flag,
> 'REF_TRANSACTION_ALLOW_PARTIAL'. When enabled, this flag allows
> individual reference updates that would typically cause the entire
> transaction to fail due to non-system-related errors to be marked as
> rejected while permitting other updates to proceed. Non-system-related
> errors include issues caused by user-provided input values, whereas
> system-related errors, such as I/O failures or memory issues, continue
> to result in a full transaction failure. This approach enhances
> flexibility while preserving transactional integrity where necessary.
> 
> The implementation introduces several key components:
> 
>    - Add 'rejection_err' field to struct `ref_update` to track failed
>      updates with failure reason.
> 
>    - Modify reference backends (files, packed, reftable) to handle
>      partial transactions by using `ref_transaction_set_rejected()`
>      instead of failing the entire transaction when
>      `REF_TRANSACTION_ALLOW_PARTIAL` is set.
> 
>    - Add `ref_transaction_for_each_rejected_update()` to let callers
>      examine which updates were rejected and why.

I think this is a much better design. I wonder if we want to signal to the caller of ref_transaction_commit() that there were ignored errors rather than forcing them to call ref_transaction_for_each_rejected() to find that out. Another possibility would be to call the callback from ref_transaction_commit() but that would mean changing the signature of ref_transaction_begin() to take the callback and user data when REF_TRANSACTION_ALLOW_PARTIAL is passed.

Best Wishes
Phillip
Show 270 quoted lines
> This foundational change enables partial transaction support throughout
> the reference subsystem. The next commit will expose this capability to
> users by adding a `--allow-partial` flag to 'git-update-ref(1)',
> providing both a user-facing feature and a testable implementation.
> 
> Signed-off-by: Karthik Nayak <karthik.188@gmail.com>
> ---
>   refs.c                  | 31 +++++++++++++++++++++++++++++++
>   refs.h                  | 22 ++++++++++++++++++++++
>   refs/files-backend.c    | 12 +++++++++++-
>   refs/packed-backend.c   | 30 ++++++++++++++++++++++++++++--
>   refs/refs-internal.h    | 13 +++++++++++++
>   refs/reftable-backend.c | 12 +++++++++++-
>   6 files changed, 116 insertions(+), 4 deletions(-)
> 
> diff --git a/refs.c b/refs.c
> index f989a46a5a..243c09c368 100644
> --- a/refs.c
> +++ b/refs.c
> @@ -1211,6 +1211,15 @@ void ref_transaction_free(struct ref_transaction *transaction)
>   	free(transaction);
>   }
>   
> +void ref_transaction_set_rejected(struct ref_transaction *transaction,
> +				  size_t update_idx,
> +				  enum transaction_error err)
> +{
> +	if (update_idx >= transaction->nr)
> +		BUG("trying to set rejection on invalid update index");
> +	transaction->updates[update_idx]->rejection_err = err;
> +}
> +
>   struct ref_update *ref_transaction_add_update(
>   		struct ref_transaction *transaction,
>   		const char *refname, unsigned int flags,
> @@ -1236,6 +1245,7 @@ struct ref_update *ref_transaction_add_update(
>   	transaction->updates[transaction->nr++] = update;
>   
>   	update->flags = flags;
> +	update->rejection_err = TRANSACTION_OK;
>   
>   	update->new_target = xstrdup_or_null(new_target);
>   	update->old_target = xstrdup_or_null(old_target);
> @@ -2726,6 +2736,27 @@ void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
>   	}
>   }
>   
> +void ref_transaction_for_each_rejected_update(struct ref_transaction *transaction,
> +					      ref_transaction_for_each_rejected_update_fn cb,
> +					      void *cb_data)
> +{
> +	if (!(transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL))
> +		return;
> +
> +	for (size_t i = 0; i < transaction->nr; i++) {
> +		struct ref_update *update = transaction->updates[i];
> +
> +		if (!update->rejection_err)
> +			continue;
> +
> +		cb(update->refname,
> +		   (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
> +		   (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
> +		   update->old_target, update->new_target,
> +		   update->rejection_err, cb_data);
> +	}
> +}
> +
>   int refs_delete_refs(struct ref_store *refs, const char *logmsg,
>   		     struct string_list *refnames, unsigned int flags)
>   {
> diff --git a/refs.h b/refs.h
> index 8e9ead174c..e4a6a8218f 100644
> --- a/refs.h
> +++ b/refs.h
> @@ -675,6 +675,13 @@ enum ref_transaction_flag {
>   	 * either be absent or null_oid.
>   	 */
>   	REF_TRANSACTION_FLAG_INITIAL = (1 << 0),
> +
> +	/*
> +	 * The transaction mechanism by default fails all updates if any conflict
> +	 * is detected. This flag allows transactions to partially apply updates
> +	 * while rejecting updates which do not match the expected state.
> +	 */
> +	REF_TRANSACTION_ALLOW_PARTIAL = (1 << 1),
>   };
>   
>   /*
> @@ -905,6 +912,21 @@ void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
>   					    ref_transaction_for_each_queued_update_fn cb,
>   					    void *cb_data);
>   
> +/*
> + * Execute the given callback function for each of the reference updates which
> + * have been rejected in the given transaction.
> + */
> +typedef void ref_transaction_for_each_rejected_update_fn(const char *refname,
> +							 const struct object_id *old_oid,
> +							 const struct object_id *new_oid,
> +							 const char *old_target,
> +							 const char *new_target,
> +							 enum transaction_error err,
> +							 void *cb_data);
> +void ref_transaction_for_each_rejected_update(struct ref_transaction *transaction,
> +					      ref_transaction_for_each_rejected_update_fn cb,
> +					      void *cb_data);
> +
>   /*
>    * Free `*transaction` and all associated data.
>    */
> diff --git a/refs/files-backend.c b/refs/files-backend.c
> index 3b0adf8bb2..d0a53c9ace 100644
> --- a/refs/files-backend.c
> +++ b/refs/files-backend.c
> @@ -2851,8 +2851,18 @@ static int files_transaction_prepare(struct ref_store *ref_store,
>   		ret = lock_ref_for_update(refs, update, transaction,
>   					  head_ref, &refnames_to_check,
>   					  err);
> -		if (ret)
> +		if (ret) {
> +			if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL &&
> +			    ret != TRANSACTION_GENERIC_ERROR) {
> +				ref_transaction_set_rejected(transaction, i, ret);
> +
> +				strbuf_setlen(err, 0);
> +				ret = TRANSACTION_OK;
> +
> +				continue;
> +			}
>   			goto cleanup;
> +		}
>   
>   		if (update->flags & REF_DELETING &&
>   		    !(update->flags & REF_LOG_ONLY) &&
> diff --git a/refs/packed-backend.c b/refs/packed-backend.c
> index 75e1ebf67d..0857204213 100644
> --- a/refs/packed-backend.c
> +++ b/refs/packed-backend.c
> @@ -1324,10 +1324,11 @@ static int packed_ref_store_remove_on_disk(struct ref_store *ref_store,
>    * remain locked when it is done.
>    */
>   static enum transaction_error write_with_updates(struct packed_ref_store *refs,
> -						 struct string_list *updates,
> +						 struct ref_transaction *transaction,
>   						 struct strbuf *err)
>   {
>   	enum transaction_error ret = TRANSACTION_GENERIC_ERROR;
> +	struct string_list *updates = &transaction->refnames;
>   	struct ref_iterator *iter = NULL;
>   	size_t i;
>   	int ok;
> @@ -1408,6 +1409,14 @@ static enum transaction_error write_with_updates(struct packed_ref_store *refs,
>   						    "reference already exists",
>   						    update->refname);
>   					ret = TRANSACTION_CREATE_EXISTS;
> +
> +					if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL) {
> +						ref_transaction_set_rejected(transaction, i, ret);
> +						strbuf_setlen(err, 0);
> +						ret = 0;
> +						continue;
> +					}
> +
>   					goto error;
>   				} else if (!oideq(&update->old_oid, iter->oid)) {
>   					strbuf_addf(err, "cannot update ref '%s': "
> @@ -1416,6 +1425,14 @@ static enum transaction_error write_with_updates(struct packed_ref_store *refs,
>   						    oid_to_hex(iter->oid),
>   						    oid_to_hex(&update->old_oid));
>   					ret = TRANSACTION_INCORRECT_OLD_VALUE;
> +
> +					if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL) {
> +						ref_transaction_set_rejected(transaction, i, ret);
> +						strbuf_setlen(err, 0);
> +						ret = 0;
> +						continue;
> +					}
> +
>   					goto error;
>   				}
>   			}
> @@ -1453,6 +1470,14 @@ static enum transaction_error write_with_updates(struct packed_ref_store *refs,
>   					    update->refname,
>   					    oid_to_hex(&update->old_oid));
>   				return TRANSACTION_NONEXISTENT_REF;
> +
> +				if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL) {
> +					ref_transaction_set_rejected(transaction, i, ret);
> +					strbuf_setlen(err, 0);
> +					ret = 0;
> +					continue;
> +				}
> +
>   				goto error;
>   			}
>   		}
> @@ -1518,6 +1543,7 @@ static enum transaction_error write_with_updates(struct packed_ref_store *refs,
>   write_error:
>   	strbuf_addf(err, "error writing to %s: %s",
>   		    get_tempfile_path(refs->tempfile), strerror(errno));
> +	ret = TRANSACTION_GENERIC_ERROR;
>   
>   error:
>   	ref_iterator_free(iter);
> @@ -1676,7 +1702,7 @@ static int packed_transaction_prepare(struct ref_store *ref_store,
>   		data->own_lock = 1;
>   	}
>   
> -	ret = write_with_updates(refs, &transaction->refnames, err);
> +	ret = write_with_updates(refs, transaction, err);
>   	if (ret)
>   		goto failure;
>   
> diff --git a/refs/refs-internal.h b/refs/refs-internal.h
> index c97045fbed..7196f2d880 100644
> --- a/refs/refs-internal.h
> +++ b/refs/refs-internal.h
> @@ -123,6 +123,11 @@ struct ref_update {
>   	 */
>   	uint64_t index;
>   
> +	/*
> +	 * Used in partial transactions to mark if a given update was rejected.
> +	 */
> +	enum transaction_error rejection_err;
> +
>   	/*
>   	 * If this ref_update was split off of a symref update via
>   	 * split_symref_update(), then this member points at that
> @@ -142,6 +147,14 @@ int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
>   		      struct object_id *oid, struct strbuf *referent,
>   		      unsigned int *type, int *failure_errno);
>   
> +/*
> + * Mark a given update as rejected with a given reason. To be used in conjuction
> + * with the `REF_TRANSACTION_ALLOW_PARTIAL` flag to allow partial transactions.
> + */
> +void ref_transaction_set_rejected(struct ref_transaction *transaction,
> +				  size_t update_idx,
> +				  enum transaction_error err);
> +
>   /*
>    * Add a ref_update with the specified properties to transaction, and
>    * return a pointer to the new object. This function does not verify
> diff --git a/refs/reftable-backend.c b/refs/reftable-backend.c
> index e1fd9c2de2..83cf8d582b 100644
> --- a/refs/reftable-backend.c
> +++ b/refs/reftable-backend.c
> @@ -1374,8 +1374,18 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
>   					    transaction->updates[i],
>   					    &refnames_to_check, head_type,
>   					    &head_referent, &referent, err);
> -		if (ret)
> +		if (ret) {
> +			if (transaction->flags & REF_TRANSACTION_ALLOW_PARTIAL &&
> +			    ret != TRANSACTION_GENERIC_ERROR) {
> +				ref_transaction_set_rejected(transaction, i, ret);
> +
> +				strbuf_setlen(err, 0);
> +				ret = TRANSACTION_OK;
> +
> +				continue;
> +			}
>   			goto done;
> +		}
>   	}
>   
>   	string_list_sort(&refnames_to_check);
> 
Karthik Nayak· Mar 3, 2025, 20:21 UTC · re: Phillip Wood · lore

Re: [PATCH v2 6/7] refs: implement partial reference transaction support

Phillip Wood <phillip.wood123@gmail.com> writes:
Hello Phillip!
Show 40 quoted lines
> Hi Karthik
>
> On 25/02/2025 09:29, Karthik Nayak wrote:
>> Git's reference transactions are all-or-nothing: either all updates
>> succeed, or none do. While this atomic behavior is generally desirable,
>> it can be suboptimal especially when using the reftable backend, where
>> batching multiple reference updates into a single transaction is more
>> efficient than performing them sequentially.
>>
>> Introduce partial transaction support with a new flag,
>> 'REF_TRANSACTION_ALLOW_PARTIAL'. When enabled, this flag allows
>> individual reference updates that would typically cause the entire
>> transaction to fail due to non-system-related errors to be marked as
>> rejected while permitting other updates to proceed. Non-system-related
>> errors include issues caused by user-provided input values, whereas
>> system-related errors, such as I/O failures or memory issues, continue
>> to result in a full transaction failure. This approach enhances
>> flexibility while preserving transactional integrity where necessary.
>>
>> The implementation introduces several key components:
>>
>>    - Add 'rejection_err' field to struct `ref_update` to track failed
>>      updates with failure reason.
>>
>>    - Modify reference backends (files, packed, reftable) to handle
>>      partial transactions by using `ref_transaction_set_rejected()`
>>      instead of failing the entire transaction when
>>      `REF_TRANSACTION_ALLOW_PARTIAL` is set.
>>
>>    - Add `ref_transaction_for_each_rejected_update()` to let callers
>>      examine which updates were rejected and why.
>
> I think this is a much better design. I wonder if we want to signal to
> the caller of ref_transaction_commit() that there were ignored errors
> rather than forcing them to call ref_transaction_for_each_rejected() to
> find that out. Another possibility would be to call the callback from
> ref_transaction_commit() but that would mean changing the signature of
> ref_transaction_begin() to take the callback and user data when
> REF_TRANSACTION_ALLOW_PARTIAL is passed.
>

Yes, I did toy around modifying `ref_transaction_*` at first, but I think the current implementation is slightly better. Users of the ref API do not have to worry about complexity of partial transactions unless they really need to. So in that case, for most users, the API remains simple and clean, and for specific users who do want partial transaction support, they can activate it via the flag and use the iterator to collect the rejections at the end.

> Best Wishes
>
> Phillip
>
[snip]
Phillip Wood· Mar 4, 2025, 10:31 UTC · re: Karthik Nayak · lore

Re: [PATCH v2 6/7] refs: implement partial reference transaction support

Hi Karthik
On 03/03/2025 20:21, Karthik Nayak wrote:
Show 47 quoted lines
> Phillip Wood <phillip.wood123@gmail.com> writes:
>> On 25/02/2025 09:29, Karthik Nayak wrote:
>>> Git's reference transactions are all-or-nothing: either all updates
>>> succeed, or none do. While this atomic behavior is generally desirable,
>>> it can be suboptimal especially when using the reftable backend, where
>>> batching multiple reference updates into a single transaction is more
>>> efficient than performing them sequentially.
>>>
>>> Introduce partial transaction support with a new flag,
>>> 'REF_TRANSACTION_ALLOW_PARTIAL'. When enabled, this flag allows
>>> individual reference updates that would typically cause the entire
>>> transaction to fail due to non-system-related errors to be marked as
>>> rejected while permitting other updates to proceed. Non-system-related
>>> errors include issues caused by user-provided input values, whereas
>>> system-related errors, such as I/O failures or memory issues, continue
>>> to result in a full transaction failure. This approach enhances
>>> flexibility while preserving transactional integrity where necessary.
>>>
>>> The implementation introduces several key components:
>>>
>>>     - Add 'rejection_err' field to struct `ref_update` to track failed
>>>       updates with failure reason.
>>>
>>>     - Modify reference backends (files, packed, reftable) to handle
>>>       partial transactions by using `ref_transaction_set_rejected()`
>>>       instead of failing the entire transaction when
>>>       `REF_TRANSACTION_ALLOW_PARTIAL` is set.
>>>
>>>     - Add `ref_transaction_for_each_rejected_update()` to let callers
>>>       examine which updates were rejected and why.
>>
>> I think this is a much better design. I wonder if we want to signal to
>> the caller of ref_transaction_commit() that there were ignored errors
>> rather than forcing them to call ref_transaction_for_each_rejected() to
>> find that out. Another possibility would be to call the callback from
>> ref_transaction_commit() but that would mean changing the signature of
>> ref_transaction_begin() to take the callback and user data when
>> REF_TRANSACTION_ALLOW_PARTIAL is passed.
>>
> 
> Yes, I did toy around modifying `ref_transaction_*` at first, but I
> think the current implementation is slightly better. Users of the ref
> API do not have to worry about complexity of partial transactions unless
> they really need to. So in that case, for most users, the API remains
> simple and clean, and for specific users who do want partial transaction
> support, they can activate it via the flag and use the iterator to
> collect the rejections at the end.

That makes sense. I have a slight concern that iterating through the errors is O(number of ref updates) rather than O(number of errors). If we expect most updates to succeed that it is a shame to have to check them all just to see there were no errors. Maybe we could be store the errors in a separate list of (update-index, error) pairs to avoid that.

Best Wishes
Phillip
Karthik Nayak· Mar 5, 2025, 14:20 UTC · re: Phillip Wood · lore

Re: [PATCH v2 6/7] refs: implement partial reference transaction support

Phillip Wood <phillip.wood123@gmail.com> writes:
Show 57 quoted lines
> Hi Karthik
>
> On 03/03/2025 20:21, Karthik Nayak wrote:
>> Phillip Wood <phillip.wood123@gmail.com> writes:
>>> On 25/02/2025 09:29, Karthik Nayak wrote:
>>>> Git's reference transactions are all-or-nothing: either all updates
>>>> succeed, or none do. While this atomic behavior is generally desirable,
>>>> it can be suboptimal especially when using the reftable backend, where
>>>> batching multiple reference updates into a single transaction is more
>>>> efficient than performing them sequentially.
>>>>
>>>> Introduce partial transaction support with a new flag,
>>>> 'REF_TRANSACTION_ALLOW_PARTIAL'. When enabled, this flag allows
>>>> individual reference updates that would typically cause the entire
>>>> transaction to fail due to non-system-related errors to be marked as
>>>> rejected while permitting other updates to proceed. Non-system-related
>>>> errors include issues caused by user-provided input values, whereas
>>>> system-related errors, such as I/O failures or memory issues, continue
>>>> to result in a full transaction failure. This approach enhances
>>>> flexibility while preserving transactional integrity where necessary.
>>>>
>>>> The implementation introduces several key components:
>>>>
>>>>     - Add 'rejection_err' field to struct `ref_update` to track failed
>>>>       updates with failure reason.
>>>>
>>>>     - Modify reference backends (files, packed, reftable) to handle
>>>>       partial transactions by using `ref_transaction_set_rejected()`
>>>>       instead of failing the entire transaction when
>>>>       `REF_TRANSACTION_ALLOW_PARTIAL` is set.
>>>>
>>>>     - Add `ref_transaction_for_each_rejected_update()` to let callers
>>>>       examine which updates were rejected and why.
>>>
>>> I think this is a much better design. I wonder if we want to signal to
>>> the caller of ref_transaction_commit() that there were ignored errors
>>> rather than forcing them to call ref_transaction_for_each_rejected() to
>>> find that out. Another possibility would be to call the callback from
>>> ref_transaction_commit() but that would mean changing the signature of
>>> ref_transaction_begin() to take the callback and user data when
>>> REF_TRANSACTION_ALLOW_PARTIAL is passed.
>>>
>>
>> Yes, I did toy around modifying `ref_transaction_*` at first, but I
>> think the current implementation is slightly better. Users of the ref
>> API do not have to worry about complexity of partial transactions unless
>> they really need to. So in that case, for most users, the API remains
>> simple and clean, and for specific users who do want partial transaction
>> support, they can activate it via the flag and use the iterator to
>> collect the rejections at the end.
>
> That makes sense. I have a slight concern that iterating through the
> errors is O(number of ref updates) rather than O(number of errors). If
> we expect most updates to succeed that it is a shame to have to check
> them all just to see there were no errors. Maybe we could be store the
> errors in a separate list of (update-index, error) pairs to avoid that.
>

That is a good point, let me add in a array inside 'ref_transaction' which will track rejected updates.

> Best Wishes
>
> Phillip
Thanks!
Karthik Nayak· Feb 25, 2025, 09:29 UTC · re: Karthik Nayak · lore

[PATCH v2 5/7] refs: introduce enum-based transaction error types

Replace preprocessor-defined transaction errors with a strongly-typed enum `transaction_error`. This change:

  - Improves type safety and function signature clarity.
  - Makes error handling more explicit and discoverable.
  - Maintains existing error cases, while adding new error cases for
    common scenarios.

This refactoring paves the way for more comprehensive error handling which we will utilize in the upcoming commits to add partial transaction support.

Signed-off-by: Karthik Nayak <karthik.188@gmail.com>
---
 refs.c                  |  44 +++++++------
 refs.h                  |  56 ++++++++++------
 refs/files-backend.c    | 167 ++++++++++++++++++++++++------------------------
 refs/packed-backend.c   |  21 +++---
 refs/refs-internal.h    |   5 +-
 refs/reftable-backend.c |  59 +++++++++--------
 6 files changed, 191 insertions(+), 161 deletions(-)
Show changes to 6 files +191 −161

refs.c, refs.h, refs/files-backend.c, refs/packed-backend.c, refs/refs-internal.h, refs/reftable-backend.c

diff --git a/refs.c b/refs.c
index 69f385f344..f989a46a5a 100644
--- a/refs.c
+++ b/refs.c
@@ -2497,18 +2497,18 @@ int ref_transaction_commit(struct ref_transaction *transaction,
 	return ret;
 }
 
-int refs_verify_refnames_available(struct ref_store *refs,
-				   const struct string_list *refnames,
-				   const struct string_list *extras,
-				   const struct string_list *skip,
-				   unsigned int initial_transaction,
-				   struct strbuf *err)
+enum transaction_error refs_verify_refnames_available(struct ref_store *refs,
+						      const struct string_list *refnames,
+						      const struct string_list *extras,
+						      const struct string_list *skip,
+						      unsigned int initial_transaction,
+						      struct strbuf *err)
 {
 	struct strbuf dirname = STRBUF_INIT;
 	struct strbuf referent = STRBUF_INIT;
 	struct ref_iterator *iter = NULL;
 	struct strset dirnames;
-	int ret = -1;
+	int ret = TRANSACTION_NAME_CONFLICT;
 
 	/*
 	 * For the sake of comments in this function, suppose that
@@ -2624,12 +2624,12 @@ int refs_verify_refnames_available(struct ref_store *refs,
 	return ret;
 }
 
-int refs_verify_refname_available(struct ref_store *refs,
-				  const char *refname,
-				  const struct string_list *extras,
-				  const struct string_list *skip,
-				  unsigned int initial_transaction,
-				  struct strbuf *err)
+enum transaction_error refs_verify_refname_available(struct ref_store *refs,
+						     const char *refname,
+						     const struct string_list *extras,
+						     const struct string_list *skip,
+						     unsigned int initial_transaction,
+						     struct strbuf *err)
 {
 	struct string_list_item item = { .string = (char *) refname };
 	struct string_list refnames = {
@@ -2817,26 +2817,28 @@ int ref_update_has_null_new_value(struct ref_update *update)
 	return !update->new_target && is_null_oid(&update->new_oid);
 }
 
-int ref_update_check_old_target(const char *referent, struct ref_update *update,
-				struct strbuf *err)
+enum transaction_error ref_update_check_old_target(const char *referent,
+					      struct ref_update *update,
+					      struct strbuf *err)
 {
 	if (!update->old_target)
 		BUG("called without old_target set");
 
 	if (!strcmp(referent, update->old_target))
-		return 0;
+		return TRANSACTION_OK;
 
-	if (!strcmp(referent, ""))
+	if (!strcmp(referent, "")) {
 		strbuf_addf(err, "verifying symref target: '%s': "
 			    "reference is missing but expected %s",
 			    ref_update_original_update_refname(update),
 			    update->old_target);
-	else
-		strbuf_addf(err, "verifying symref target: '%s': "
-			    "is at %s but expected %s",
+		return TRANSACTION_NONEXISTENT_REF;
+	}
+
+	strbuf_addf(err, "verifying symref target: '%s': is at %s but expected %s",
 			    ref_update_original_update_refname(update),
 			    referent, update->old_target);
-	return -1;
+	return TRANSACTION_INCORRECT_OLD_VALUE;
 }
 
 struct migration_data {
diff --git a/refs.h b/refs.h
index b14ba1f9ff..8e9ead174c 100644
--- a/refs.h
+++ b/refs.h
@@ -16,6 +16,31 @@ struct worktree;
 enum ref_storage_format ref_storage_format_by_name(const char *name);
 const char *ref_storage_format_to_name(enum ref_storage_format ref_storage_format);
 
+/*
+ * enum transaction_error represents the following return codes:
+ * TRANSACTION_OK: success code.
+ * TRANSACTION_GENERIC_ERROR error_code: default error code.
+ * TRANSACTION_NAME_CONFLICT error_code: ref name conflict like A vs A/B.
+ * TRANSACTION_CREATE_EXISTS error_code: ref to be created already exists.
+ * TRANSACTION_NONEXISTENT_REF error_code: ref expected but doesn't exist.
+ * TRANSACTION_INCORRECT_OLD_VALUE error_code: provided old_oid or old_target of
+ * reference doesn't match actual.
+ * TRANSACTION_INVALID_NEW_VALUE error_code: provided new_oid or new_target is
+ * invalid.
+ * TRANSACTION_EXPECTED_SYMREF error_code: expected ref to be symref, but is a
+ * regular ref.
+ */
+enum transaction_error {
+	TRANSACTION_OK = 0,
+	TRANSACTION_GENERIC_ERROR = -1,
+	TRANSACTION_NAME_CONFLICT = -2,
+	TRANSACTION_CREATE_EXISTS = -3,
+	TRANSACTION_NONEXISTENT_REF = -4,
+	TRANSACTION_INCORRECT_OLD_VALUE = -5,
+	TRANSACTION_INVALID_NEW_VALUE = -6,
+	TRANSACTION_EXPECTED_SYMREF = -7,
+};
+
 /*
  * Resolve a reference, recursively following symbolic references.
  *
@@ -117,24 +142,24 @@ int refs_read_symbolic_ref(struct ref_store *ref_store, const char *refname,
  *
  * extras and skip must be sorted.
  */
-int refs_verify_refname_available(struct ref_store *refs,
-				  const char *refname,
-				  const struct string_list *extras,
-				  const struct string_list *skip,
-				  unsigned int initial_transaction,
-				  struct strbuf *err);
+enum transaction_error refs_verify_refname_available(struct ref_store *refs,
+						     const char *refname,
+						     const struct string_list *extras,
+						     const struct string_list *skip,
+						     unsigned int initial_transaction,
+						     struct strbuf *err);
 
 /*
  * Same as `refs_verify_refname_available()`, but checking for a list of
  * refnames instead of only a single item. This is more efficient in the case
  * where one needs to check multiple refnames.
  */
-int refs_verify_refnames_available(struct ref_store *refs,
-				   const struct string_list *refnames,
-				   const struct string_list *extras,
-				   const struct string_list *skip,
-				   unsigned int initial_transaction,
-				   struct strbuf *err);
+enum transaction_error refs_verify_refnames_available(struct ref_store *refs,
+						      const struct string_list *refnames,
+						      const struct string_list *extras,
+						      const struct string_list *skip,
+						      unsigned int initial_transaction,
+						      struct strbuf *err);
 
 int refs_ref_exists(struct ref_store *refs, const char *refname);
 
@@ -830,13 +855,6 @@ int ref_transaction_verify(struct ref_transaction *transaction,
 			   unsigned int flags,
 			   struct strbuf *err);
 
-/* Naming conflict (for example, the ref names A and A/B conflict). */
-#define TRANSACTION_NAME_CONFLICT -1
-/* When only creation was requested, but the ref already exists. */
-#define TRANSACTION_CREATE_EXISTS -2
-/* All other errors. */
-#define TRANSACTION_GENERIC_ERROR -3
-
 /*
  * Perform the preparatory stages of committing `transaction`. Acquire
  * any needed locks, check preconditions, etc.; basically, do as much
diff --git a/refs/files-backend.c b/refs/files-backend.c
index 7c6a0b3478..3b0adf8bb2 100644
--- a/refs/files-backend.c
+++ b/refs/files-backend.c
@@ -676,19 +676,19 @@ static void unlock_ref(struct ref_lock *lock)
  *   avoided, namely if we were successfully able to read the ref
  * - Generate informative error messages in the case of failure
  */
-static int lock_raw_ref(struct files_ref_store *refs,
-			const char *refname, int mustexist,
-			struct string_list *refnames_to_check,
-			const struct string_list *extras,
-			struct ref_lock **lock_p,
-			struct strbuf *referent,
-			unsigned int *type,
-			struct strbuf *err)
+static enum transaction_error lock_raw_ref(struct files_ref_store *refs,
+					   const char *refname, int mustexist,
+					   struct string_list *refnames_to_check,
+					   const struct string_list *extras,
+					   struct ref_lock **lock_p,
+					   struct strbuf *referent,
+					   unsigned int *type,
+					   struct strbuf *err)
 {
+	enum transaction_error ret = TRANSACTION_GENERIC_ERROR;
 	struct ref_lock *lock;
 	struct strbuf ref_file = STRBUF_INIT;
 	int attempts_remaining = 3;
-	int ret = TRANSACTION_GENERIC_ERROR;
 	int failure_errno;
 
 	assert(err);
@@ -728,6 +728,7 @@ static int lock_raw_ref(struct files_ref_store *refs,
 				strbuf_reset(err);
 				strbuf_addf(err, "unable to resolve reference '%s'",
 					    refname);
+				ret = TRANSACTION_NONEXISTENT_REF;
 			} else {
 				/*
 				 * The error message set by
@@ -788,6 +789,7 @@ static int lock_raw_ref(struct files_ref_store *refs,
 				/* Garden variety missing reference. */
 				strbuf_addf(err, "unable to resolve reference '%s'",
 					    refname);
+				ret = TRANSACTION_NONEXISTENT_REF;
 				goto error_return;
 			} else {
 				/*
@@ -820,6 +822,7 @@ static int lock_raw_ref(struct files_ref_store *refs,
 				/* Garden variety missing reference. */
 				strbuf_addf(err, "unable to resolve reference '%s'",
 					    refname);
+				ret = TRANSACTION_NONEXISTENT_REF;
 				goto error_return;
 			} else if (remove_dir_recursively(&ref_file,
 							  REMOVE_DIR_EMPTY_ONLY)) {
@@ -863,7 +866,7 @@ static int lock_raw_ref(struct files_ref_store *refs,
 		string_list_insert(refnames_to_check, refname);
 	}
 
-	ret = 0;
+	ret = TRANSACTION_OK;
 	goto out;
 
 error_return:
@@ -1517,10 +1520,10 @@ static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
 	return ret;
 }
 
-static int write_ref_to_lockfile(struct files_ref_store *refs,
-				 struct ref_lock *lock,
-				 const struct object_id *oid,
-				 int skip_oid_verification, struct strbuf *err);
+static enum transaction_error write_ref_to_lockfile(struct files_ref_store *refs,
+						    struct ref_lock *lock,
+						    const struct object_id *oid,
+						    int skip_oid_verification, 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,
@@ -1926,10 +1929,11 @@ static int files_log_ref_write(struct files_ref_store *refs,
  * Write oid into the open lockfile, then close the lockfile. On
  * errors, rollback the lockfile, fill in *err and return -1.
  */
-static int write_ref_to_lockfile(struct files_ref_store *refs,
-				 struct ref_lock *lock,
-				 const struct object_id *oid,
-				 int skip_oid_verification, struct strbuf *err)
+static enum transaction_error write_ref_to_lockfile(struct files_ref_store *refs,
+						    struct ref_lock *lock,
+						    const struct object_id *oid,
+						    int skip_oid_verification,
+						    struct strbuf *err)
 {
 	static char term = '\n';
 	struct object *o;
@@ -1943,7 +1947,7 @@ static int write_ref_to_lockfile(struct files_ref_store *refs,
 				"trying to write ref '%s' with nonexistent object %s",
 				lock->ref_name, oid_to_hex(oid));
 			unlock_ref(lock);
-			return -1;
+			return TRANSACTION_INVALID_NEW_VALUE;
 		}
 		if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
 			strbuf_addf(
@@ -1951,7 +1955,7 @@ static int write_ref_to_lockfile(struct files_ref_store *refs,
 				"trying to write non-commit object %s to branch '%s'",
 				oid_to_hex(oid), lock->ref_name);
 			unlock_ref(lock);
-			return -1;
+			return TRANSACTION_INVALID_NEW_VALUE;
 		}
 	}
 	fd = get_lock_file_fd(&lock->lk);
@@ -1962,9 +1966,9 @@ static int write_ref_to_lockfile(struct files_ref_store *refs,
 		strbuf_addf(err,
 			    "couldn't write '%s'", get_lock_file_path(&lock->lk));
 		unlock_ref(lock);
-		return -1;
+		return TRANSACTION_GENERIC_ERROR;
 	}
-	return 0;
+	return TRANSACTION_OK;
 }
 
 /*
@@ -2376,9 +2380,10 @@ static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_st
  * If update is a direct update of head_ref (the reference pointed to
  * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
  */
-static int split_head_update(struct ref_update *update,
-			     struct ref_transaction *transaction,
-			     const char *head_ref, struct strbuf *err)
+static enum transaction_error split_head_update(struct ref_update *update,
+						struct ref_transaction *transaction,
+						const char *head_ref,
+						struct strbuf *err)
 {
 	struct ref_update *new_update;
 
@@ -2386,10 +2391,10 @@ static int split_head_update(struct ref_update *update,
 	    (update->flags & REF_SKIP_CREATE_REFLOG) ||
 	    (update->flags & REF_IS_PRUNING) ||
 	    (update->flags & REF_UPDATE_VIA_HEAD))
-		return 0;
+		return TRANSACTION_OK;
 
 	if (strcmp(update->refname, head_ref))
-		return 0;
+		return TRANSACTION_OK;
 
 	/*
 	 * First make sure that HEAD is not already in the
@@ -2419,7 +2424,7 @@ static int split_head_update(struct ref_update *update,
 	if (strcmp(new_update->refname, "HEAD"))
 		BUG("%s unexpectedly not 'HEAD'", new_update->refname);
 
-	return 0;
+	return TRANSACTION_OK;
 }
 
 /*
@@ -2430,10 +2435,10 @@ static int split_head_update(struct ref_update *update,
  * Note that the new update will itself be subject to splitting when
  * the iteration gets to it.
  */
-static int split_symref_update(struct ref_update *update,
-			       const char *referent,
-			       struct ref_transaction *transaction,
-			       struct strbuf *err)
+static enum transaction_error split_symref_update(struct ref_update *update,
+						  const char *referent,
+						  struct ref_transaction *transaction,
+						  struct strbuf *err)
 {
 	struct ref_update *new_update;
 	unsigned int new_flags;
@@ -2482,7 +2487,7 @@ static int split_symref_update(struct ref_update *update,
 	update->flags |= REF_LOG_ONLY | REF_NO_DEREF;
 	update->flags &= ~REF_HAVE_OLD;
 
-	return 0;
+	return TRANSACTION_OK;
 }
 
 /*
@@ -2491,34 +2496,32 @@ static int split_symref_update(struct ref_update *update,
  * everything is OK, return 0; otherwise, write an error message to
  * err and return -1.
  */
-static int check_old_oid(struct ref_update *update, struct object_id *oid,
-			 struct strbuf *err)
+static enum transaction_error check_old_oid(struct ref_update *update,
+					    struct object_id *oid,
+					    struct strbuf *err)
 {
-	int ret = TRANSACTION_GENERIC_ERROR;
-
 	if (!(update->flags & REF_HAVE_OLD) ||
 		   oideq(oid, &update->old_oid))
-		return 0;
+		return TRANSACTION_OK;
 
 	if (is_null_oid(&update->old_oid)) {
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference already exists",
 			    ref_update_original_update_refname(update));
-		ret = TRANSACTION_CREATE_EXISTS;
-	}
-	else if (is_null_oid(oid))
+		return TRANSACTION_CREATE_EXISTS;
+	} else if (is_null_oid(oid)) {
 		strbuf_addf(err, "cannot lock ref '%s': "
 			    "reference is missing but expected %s",
 			    ref_update_original_update_refname(update),
 			    oid_to_hex(&update->old_oid));
-	else
-		strbuf_addf(err, "cannot lock ref '%s': "
-			    "is at %s but expected %s",
-			    ref_update_original_update_refname(update),
-			    oid_to_hex(oid),
-			    oid_to_hex(&update->old_oid));
+		return TRANSACTION_NONEXISTENT_REF;
+	}
 
-	return ret;
+	strbuf_addf(err, "cannot lock ref '%s': is at %s but expected %s",
+		    ref_update_original_update_refname(update), oid_to_hex(oid),
+		    oid_to_hex(&update->old_oid));
+
+	return TRANSACTION_INCORRECT_OLD_VALUE;
 }
 
 struct files_transaction_backend_data {
@@ -2540,17 +2543,17 @@ struct files_transaction_backend_data {
  * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
  *   update of HEAD.
  */
-static int lock_ref_for_update(struct files_ref_store *refs,
-			       struct ref_update *update,
-			       struct ref_transaction *transaction,
-			       const char *head_ref,
-			       struct string_list *refnames_to_check,
-			       struct strbuf *err)
+static enum transaction_error lock_ref_for_update(struct files_ref_store *refs,
+						  struct ref_update *update,
+						  struct ref_transaction *transaction,
+						  const char *head_ref,
+						  struct string_list *refnames_to_check,
+						  struct strbuf *err)
 {
 	struct strbuf referent = STRBUF_INIT;
 	int mustexist = ref_update_expects_existing_old_ref(update);
 	struct files_transaction_backend_data *backend_data;
-	int ret = 0;
+	enum transaction_error ret = TRANSACTION_OK;
 	struct ref_lock *lock;
 
 	files_assert_main_repository(refs, "lock_ref_for_update");
@@ -2607,16 +2610,12 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 				}
 			}
 
-			if (update->old_target) {
-				if (ref_update_check_old_target(referent.buf, update, err)) {
-					ret = TRANSACTION_GENERIC_ERROR;
-					goto out;
-				}
-			} else {
+			if (update->old_target)
+				ret = ref_update_check_old_target(referent.buf, update, err);
+			else
 				ret = check_old_oid(update, &lock->old_oid, err);
-				if  (ret) {
-					goto out;
-				}
+			if (ret) {
+				goto out;
 			}
 		} else {
 			/*
@@ -2644,7 +2643,7 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 					   "but is a regular ref"),
 				    ref_update_original_update_refname(update),
 				    update->old_target);
-			ret = TRANSACTION_GENERIC_ERROR;
+			ret = TRANSACTION_EXPECTED_SYMREF;
 			goto out;
 		} else {
 			ret = check_old_oid(update, &lock->old_oid, err);
@@ -2693,25 +2692,27 @@ static int lock_ref_for_update(struct files_ref_store *refs,
 			 * The reference already has the desired
 			 * value, so we don't need to write it.
 			 */
-		} else if (write_ref_to_lockfile(
-				   refs, lock, &update->new_oid,
-				   update->flags & REF_SKIP_OID_VERIFICATION,
-				   err)) {
-			char *write_err = strbuf_detach(err, NULL);
-
-			/*
-			 * The lock was freed upon failure of
-			 * write_ref_to_lockfile():
-			 */
-			update->backend_data = NULL;
-			strbuf_addf(err,
-				    "cannot update ref '%s': %s",
-				    update->refname, write_err);
-			free(write_err);
-			ret = TRANSACTION_GENERIC_ERROR;
-			goto out;
 		} else {
-			update->flags |= REF_NEEDS_COMMIT;
+			ret = write_ref_to_lockfile(
+				refs, lock, &update->new_oid,
+				update->flags & REF_SKIP_OID_VERIFICATION,
+				err);
+			if (ret) {
+				char *write_err = strbuf_detach(err, NULL);
+
+				/*
+				 * The lock was freed upon failure of
+				 * write_ref_to_lockfile():
+				 */
+				update->backend_data = NULL;
+				strbuf_addf(err,
+					    "cannot update ref '%s': %s",
+					    update->refname, write_err);
+				free(write_err);
+				goto out;
+			} else {
+				update->flags |= REF_NEEDS_COMMIT;
+			}
 		}
 	}
 	if (!(update->flags & REF_NEEDS_COMMIT)) {
diff --git a/refs/packed-backend.c b/refs/packed-backend.c
index 3247871574..75e1ebf67d 100644
--- a/refs/packed-backend.c
+++ b/refs/packed-backend.c
@@ -1323,10 +1323,11 @@ static int packed_ref_store_remove_on_disk(struct ref_store *ref_store,
  * The packfile must be locked before calling this function and will
  * remain locked when it is done.
  */
-static int write_with_updates(struct packed_ref_store *refs,
-			      struct string_list *updates,
-			      struct strbuf *err)
+static enum transaction_error write_with_updates(struct packed_ref_store *refs,
+						 struct string_list *updates,
+						 struct strbuf *err)
 {
+	enum transaction_error ret = TRANSACTION_GENERIC_ERROR;
 	struct ref_iterator *iter = NULL;
 	size_t i;
 	int ok;
@@ -1350,7 +1351,7 @@ static int write_with_updates(struct packed_ref_store *refs,
 		strbuf_addf(err, "unable to create file %s: %s",
 			    sb.buf, strerror(errno));
 		strbuf_release(&sb);
-		return -1;
+		return TRANSACTION_GENERIC_ERROR;
 	}
 	strbuf_release(&sb);
 
@@ -1406,6 +1407,7 @@ static int write_with_updates(struct packed_ref_store *refs,
 					strbuf_addf(err, "cannot update ref '%s': "
 						    "reference already exists",
 						    update->refname);
+					ret = TRANSACTION_CREATE_EXISTS;
 					goto error;
 				} else if (!oideq(&update->old_oid, iter->oid)) {
 					strbuf_addf(err, "cannot update ref '%s': "
@@ -1413,6 +1415,7 @@ static int write_with_updates(struct packed_ref_store *refs,
 						    update->refname,
 						    oid_to_hex(iter->oid),
 						    oid_to_hex(&update->old_oid));
+					ret = TRANSACTION_INCORRECT_OLD_VALUE;
 					goto error;
 				}
 			}
@@ -1449,6 +1452,7 @@ static int write_with_updates(struct packed_ref_store *refs,
 					    "reference is missing but expected %s",
 					    update->refname,
 					    oid_to_hex(&update->old_oid));
+				return TRANSACTION_NONEXISTENT_REF;
 				goto error;
 			}
 		}
@@ -1506,10 +1510,10 @@ static int write_with_updates(struct packed_ref_store *refs,
 			    strerror(errno));
 		strbuf_release(&sb);
 		delete_tempfile(&refs->tempfile);
-		return -1;
+		return TRANSACTION_GENERIC_ERROR;
 	}
 
-	return 0;
+	return TRANSACTION_OK;
 
 write_error:
 	strbuf_addf(err, "error writing to %s: %s",
@@ -1518,7 +1522,7 @@ static int write_with_updates(struct packed_ref_store *refs,
 error:
 	ref_iterator_free(iter);
 	delete_tempfile(&refs->tempfile);
-	return -1;
+	return ret;
 }
 
 int is_packed_transaction_needed(struct ref_store *ref_store,
@@ -1672,7 +1676,8 @@ static int packed_transaction_prepare(struct ref_store *ref_store,
 		data->own_lock = 1;
 	}
 
-	if (write_with_updates(refs, &transaction->refnames, err))
+	ret = write_with_updates(refs, &transaction->refnames, err);
+	if (ret)
 		goto failure;
 
 	transaction->state = REF_TRANSACTION_PREPARED;
diff --git a/refs/refs-internal.h b/refs/refs-internal.h
index 4b7fc8f1ab..c97045fbed 100644
--- a/refs/refs-internal.h
+++ b/refs/refs-internal.h
@@ -769,8 +769,9 @@ int ref_update_has_null_new_value(struct ref_update *update);
  * If everything is OK, return 0; otherwise, write an error message to
  * err and return -1.
  */
-int ref_update_check_old_target(const char *referent, struct ref_update *update,
-				struct strbuf *err);
+enum transaction_error ref_update_check_old_target(const char *referent,
+					      struct ref_update *update,
+					      struct strbuf *err);
 
 /*
  * Check if the ref must exist, this means that the old_oid or
diff --git a/refs/reftable-backend.c b/refs/reftable-backend.c
index 2c1e2995de..e1fd9c2de2 100644
--- a/refs/reftable-backend.c
+++ b/refs/reftable-backend.c
@@ -1069,20 +1069,20 @@ static int queue_transaction_update(struct reftable_ref_store *refs,
 	return 0;
 }
 
-static int prepare_single_update(struct reftable_ref_store *refs,
-				 struct reftable_transaction_data *tx_data,
-				 struct ref_transaction *transaction,
-				 struct reftable_backend *be,
-				 struct ref_update *u,
-				 struct string_list *refnames_to_check,
-				 unsigned int head_type,
-				 struct strbuf *head_referent,
-				 struct strbuf *referent,
-				 struct strbuf *err)
+static enum transaction_error prepare_single_update(struct reftable_ref_store *refs,
+						    struct reftable_transaction_data *tx_data,
+						    struct ref_transaction *transaction,
+						    struct reftable_backend *be,
+						    struct ref_update *u,
+						    struct string_list *refnames_to_check,
+						    unsigned int head_type,
+						    struct strbuf *head_referent,
+						    struct strbuf *referent,
+						    struct strbuf *err)
 {
+	enum transaction_error ret = TRANSACTION_OK;
 	struct object_id current_oid = {0};
 	const char *rewritten_ref;
-	int ret = 0;
 
 	/*
 	 * There is no need to reload the respective backends here as
@@ -1093,7 +1093,7 @@ static int prepare_single_update(struct reftable_ref_store *refs,
 	 */
 	ret = backend_for(&be, refs, u->refname, &rewritten_ref, 0);
 	if (ret)
-		return ret;
+		return TRANSACTION_GENERIC_ERROR;
 
 	/* Verify that the new object ID is valid. */
 	if ((u->flags & REF_HAVE_NEW) && !is_null_oid(&u->new_oid) &&
@@ -1104,13 +1104,13 @@ static int prepare_single_update(struct reftable_ref_store *refs,
 			strbuf_addf(err,
 				    _("trying to write ref '%s' with nonexistent object %s"),
 				    u->refname, oid_to_hex(&u->new_oid));
-			return -1;
+			return TRANSACTION_INVALID_NEW_VALUE;
 		}
 
 		if (o->type != OBJ_COMMIT && is_branch(u->refname)) {
 			strbuf_addf(err, _("trying to write non-commit object %s to branch '%s'"),
 				    oid_to_hex(&u->new_oid), u->refname);
-			return -1;
+			return TRANSACTION_INVALID_NEW_VALUE;
 		}
 	}
 
@@ -1147,7 +1147,7 @@ static int prepare_single_update(struct reftable_ref_store *refs,
 	ret = reftable_backend_read_ref(be, rewritten_ref,
 					&current_oid, referent, &u->type);
 	if (ret < 0)
-		return ret;
+		return TRANSACTION_GENERIC_ERROR;
 	if (ret > 0 && !ref_update_expects_existing_old_ref(u)) {
 		/*
 		 * The reference does not exist, and we either have no
@@ -1168,7 +1168,7 @@ static int prepare_single_update(struct reftable_ref_store *refs,
 			ret = queue_transaction_update(refs, tx_data, u,
 						       &current_oid, err);
 			if (ret)
-				return ret;
+				return TRANSACTION_GENERIC_ERROR;
 		}
 
 		return 0;
@@ -1180,7 +1180,7 @@ static int prepare_single_update(struct reftable_ref_store *refs,
 
 				   "unable to resolve reference '%s'"),
 			    ref_update_original_update_refname(u), u->refname);
-		return -1;
+		return TRANSACTION_NONEXISTENT_REF;
 	}
 
 	if (u->type & REF_ISSYMREF) {
@@ -1196,7 +1196,7 @@ static int prepare_single_update(struct reftable_ref_store *refs,
 			if (u->flags & REF_HAVE_OLD && !resolved) {
 				strbuf_addf(err, _("cannot lock ref '%s': "
 						   "error reading reference"), u->refname);
-				return -1;
+				return TRANSACTION_GENERIC_ERROR;
 			}
 		} else {
 			struct ref_update *new_update;
@@ -1255,11 +1255,12 @@ static int prepare_single_update(struct reftable_ref_store *refs,
 					   "but is a regular ref"),
 				    ref_update_original_update_refname(u),
 				    u->old_target);
-			return -1;
+			return TRANSACTION_EXPECTED_SYMREF;
 		}
 
-		if (ref_update_check_old_target(referent->buf, u, err)) {
-			return -1;
+		ret = ref_update_check_old_target(referent->buf, u, err);
+		if (ret) {
+			return ret;
 		}
 	} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
 		if (is_null_oid(&u->old_oid)) {
@@ -1268,18 +1269,21 @@ static int prepare_single_update(struct reftable_ref_store *refs,
 				    ref_update_original_update_refname(u));
 			return TRANSACTION_CREATE_EXISTS;
 		}
-		else if (is_null_oid(&current_oid))
+		else if (is_null_oid(&current_oid)) {
 			strbuf_addf(err, _("cannot lock ref '%s': "
 					   "reference is missing but expected %s"),
 				    ref_update_original_update_refname(u),
 				    oid_to_hex(&u->old_oid));
-		else
+			return TRANSACTION_NONEXISTENT_REF;
+
+		} else {
 			strbuf_addf(err, _("cannot lock ref '%s': "
 					   "is at %s but expected %s"),
 				    ref_update_original_update_refname(u),
 				    oid_to_hex(&current_oid),
 				    oid_to_hex(&u->old_oid));
-		return TRANSACTION_NAME_CONFLICT;
+			return TRANSACTION_INCORRECT_OLD_VALUE;
+		}
 	}
 
 	/*
@@ -1296,10 +1300,10 @@ static int prepare_single_update(struct reftable_ref_store *refs,
 	if ((u->type & REF_ISSYMREF) ||
 	    (u->flags & REF_LOG_ONLY) ||
 	    (u->flags & REF_HAVE_NEW && !oideq(&current_oid, &u->new_oid)))
-		return queue_transaction_update(refs, tx_data, u,
-					       &current_oid, err);
+		if (queue_transaction_update(refs, tx_data, u, &current_oid, err))
+			return TRANSACTION_GENERIC_ERROR;
 
-	return 0;
+	return TRANSACTION_OK;
 }
 
 static int reftable_be_transaction_prepare(struct ref_store *ref_store,
@@ -1386,7 +1390,6 @@ static int reftable_be_transaction_prepare(struct ref_store *ref_store,
 	transaction->state = REF_TRANSACTION_PREPARED;
 
 done:
-	assert(ret != REFTABLE_API_ERROR);
 	if (ret < 0) {
 		free_transaction_data(tx_data);
 		transaction->state = REF_TRANSACTION_CLOSED;
-- 
2.47.2
Patrick Steinhardt· Feb 25, 2025, 11:08 UTC · re: Karthik Nayak · lore

Re: [PATCH v2 5/7] refs: introduce enum-based transaction error types

On Tue, Feb 25, 2025 at 10:29:08AM +0100, Karthik Nayak wrote:
Show 32 quoted lines
> diff --git a/refs.h b/refs.h
> index b14ba1f9ff..8e9ead174c 100644
> --- a/refs.h
> +++ b/refs.h
> @@ -16,6 +16,31 @@ struct worktree;
>  enum ref_storage_format ref_storage_format_by_name(const char *name);
>  const char *ref_storage_format_to_name(enum ref_storage_format ref_storage_format);
>  
> +/*
> + * enum transaction_error represents the following return codes:
> + * TRANSACTION_OK: success code.
> + * TRANSACTION_GENERIC_ERROR error_code: default error code.
> + * TRANSACTION_NAME_CONFLICT error_code: ref name conflict like A vs A/B.
> + * TRANSACTION_CREATE_EXISTS error_code: ref to be created already exists.
> + * TRANSACTION_NONEXISTENT_REF error_code: ref expected but doesn't exist.
> + * TRANSACTION_INCORRECT_OLD_VALUE error_code: provided old_oid or old_target of
> + * reference doesn't match actual.
> + * TRANSACTION_INVALID_NEW_VALUE error_code: provided new_oid or new_target is
> + * invalid.
> + * TRANSACTION_EXPECTED_SYMREF error_code: expected ref to be symref, but is a
> + * regular ref.
> + */
> +enum transaction_error {
> +	TRANSACTION_OK = 0,
> +	TRANSACTION_GENERIC_ERROR = -1,
> +	TRANSACTION_NAME_CONFLICT = -2,
> +	TRANSACTION_CREATE_EXISTS = -3,
> +	TRANSACTION_NONEXISTENT_REF = -4,
> +	TRANSACTION_INCORRECT_OLD_VALUE = -5,
> +	TRANSACTION_INVALID_NEW_VALUE = -6,
> +	TRANSACTION_EXPECTED_SYMREF = -7,
> +};
Nit: how about we name this `ref_transaction_error` and adapt the the
enum values accordingly? We may eventually also introduce similar errors
for the object database, so it may make sense to have the errors be
specific. Doing both the enum and changing the name might be a bit hard
to review, so we could also rename in a preparatory commit. Or we just
punt on it for now and do it once it becomes necessary, that would also
be fine with me.

I also wonder whether we really want to introduce `TRANSACTION_OK`. It's always a bit of a mouthful, and in many cases one ends up with a mixture of `ret < 0`, `ret != TRANSACTION_OK` and `ret != 0`, which may lead to confusion. Continuing to use `0` for the successful case should be fine.

Show 14 quoted lines
> diff --git a/refs/packed-backend.c b/refs/packed-backend.c
> index 3247871574..75e1ebf67d 100644
> --- a/refs/packed-backend.c
> +++ b/refs/packed-backend.c
> @@ -1672,7 +1676,8 @@ static int packed_transaction_prepare(struct ref_store *ref_store,
>  		data->own_lock = 1;
>  	}
>  
> -	if (write_with_updates(refs, &transaction->refnames, err))
> +	ret = write_with_updates(refs, &transaction->refnames, err);
> +	if (ret)
>  		goto failure;
>  
>  	transaction->state = REF_TRANSACTION_PREPARED;

Do we also want to change the local variable declaration of `int ret` to use the new type?

Show 20 quoted lines
> diff --git a/refs/reftable-backend.c b/refs/reftable-backend.c
> index 2c1e2995de..e1fd9c2de2 100644
> --- a/refs/reftable-backend.c
> +++ b/refs/reftable-backend.c
> @@ -1255,11 +1255,12 @@ static int prepare_single_update(struct reftable_ref_store *refs,
>  					   "but is a regular ref"),
>  				    ref_update_original_update_refname(u),
>  				    u->old_target);
> -			return -1;
> +			return TRANSACTION_EXPECTED_SYMREF;
>  		}
>  
> -		if (ref_update_check_old_target(referent->buf, u, err)) {
> -			return -1;
> +		ret = ref_update_check_old_target(referent->buf, u, err);
> +		if (ret) {
> +			return ret;
>  		}
>  	} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
>  		if (is_null_oid(&u->old_oid)) {
Nit: superfluous braces that we could remove while at it.
Patrick
Karthik Nayak· Mar 3, 2025, 20:12 UTC · re: Patrick Steinhardt · lore

Re: [PATCH v2 5/7] refs: introduce enum-based transaction error types

Patrick Steinhardt <ps@pks.im> writes:
Show 42 quoted lines
> On Tue, Feb 25, 2025 at 10:29:08AM +0100, Karthik Nayak wrote:
>> diff --git a/refs.h b/refs.h
>> index b14ba1f9ff..8e9ead174c 100644
>> --- a/refs.h
>> +++ b/refs.h
>> @@ -16,6 +16,31 @@ struct worktree;
>>  enum ref_storage_format ref_storage_format_by_name(const char *name);
>>  const char *ref_storage_format_to_name(enum ref_storage_format ref_storage_format);
>>
>> +/*
>> + * enum transaction_error represents the following return codes:
>> + * TRANSACTION_OK: success code.
>> + * TRANSACTION_GENERIC_ERROR error_code: default error code.
>> + * TRANSACTION_NAME_CONFLICT error_code: ref name conflict like A vs A/B.
>> + * TRANSACTION_CREATE_EXISTS error_code: ref to be created already exists.
>> + * TRANSACTION_NONEXISTENT_REF error_code: ref expected but doesn't exist.
>> + * TRANSACTION_INCORRECT_OLD_VALUE error_code: provided old_oid or old_target of
>> + * reference doesn't match actual.
>> + * TRANSACTION_INVALID_NEW_VALUE error_code: provided new_oid or new_target is
>> + * invalid.
>> + * TRANSACTION_EXPECTED_SYMREF error_code: expected ref to be symref, but is a
>> + * regular ref.
>> + */
>> +enum transaction_error {
>> +	TRANSACTION_OK = 0,
>> +	TRANSACTION_GENERIC_ERROR = -1,
>> +	TRANSACTION_NAME_CONFLICT = -2,
>> +	TRANSACTION_CREATE_EXISTS = -3,
>> +	TRANSACTION_NONEXISTENT_REF = -4,
>> +	TRANSACTION_INCORRECT_OLD_VALUE = -5,
>> +	TRANSACTION_INVALID_NEW_VALUE = -6,
>> +	TRANSACTION_EXPECTED_SYMREF = -7,
>> +};
>
> Nit: how about we name this `ref_transaction_error` and adapt the the
> enum values accordingly? We may eventually also introduce similar errors
> for the object database, so it may make sense to have the errors be
> specific. Doing both the enum and changing the name might be a bit hard
> to review, so we could also rename in a preparatory commit. Or we just
> punt on it for now and do it once it becomes necessary, that would also
> be fine with me.
>

I'm happy to rename it, should be easier now. We can always change later if needed.

Show 5 quoted lines
> I also wonder whether we really want to introduce `TRANSACTION_OK`. It's
> always a bit of a mouthful, and in many cases one ends up with a mixture
> of `ret < 0`, `ret != TRANSACTION_OK` and `ret != 0`, which may lead to
> confusion. Continuing to use `0` for the successful case should be fine.
>
Fair enough, let me remove it!
Show 18 quoted lines
>> diff --git a/refs/packed-backend.c b/refs/packed-backend.c
>> index 3247871574..75e1ebf67d 100644
>> --- a/refs/packed-backend.c
>> +++ b/refs/packed-backend.c
>> @@ -1672,7 +1676,8 @@ static int packed_transaction_prepare(struct ref_store *ref_store,
>>  		data->own_lock = 1;
>>  	}
>>
>> -	if (write_with_updates(refs, &transaction->refnames, err))
>> +	ret = write_with_updates(refs, &transaction->refnames, err);
>> +	if (ret)
>>  		goto failure;
>>
>>  	transaction->state = REF_TRANSACTION_PREPARED;
>
> Do we also want to change the local variable declaration of `int ret` to
> use the new type?
>
Yes! Good catch.
Show 23 quoted lines
>> diff --git a/refs/reftable-backend.c b/refs/reftable-backend.c
>> index 2c1e2995de..e1fd9c2de2 100644
>> --- a/refs/reftable-backend.c
>> +++ b/refs/reftable-backend.c
>> @@ -1255,11 +1255,12 @@ static int prepare_single_update(struct reftable_ref_store *refs,
>>  					   "but is a regular ref"),
>>  				    ref_update_original_update_refname(u),
>>  				    u->old_target);
>> -			return -1;
>> +			return TRANSACTION_EXPECTED_SYMREF;
>>  		}
>>
>> -		if (ref_update_check_old_target(referent->buf, u, err)) {
>> -			return -1;
>> +		ret = ref_update_check_old_target(referent->buf, u, err);
>> +		if (ret) {
>> +			return ret;
>>  		}
>>  	} else if ((u->flags & REF_HAVE_OLD) && !oideq(&current_oid, &u->old_oid)) {
>>  		if (is_null_oid(&u->old_oid)) {
>
> Nit: superfluous braces that we could remove while at it.
>
Indeed, will fix.
> Patrick
Karthik Nayak· Feb 25, 2025, 09:29 UTC · re: Karthik Nayak · lore

[PATCH v2 7/7] update-ref: add --allow-partial flag for stdin mode

When updating multiple references through stdin, Git's update-ref command normally aborts the entire transaction if any single update fails. While this atomic behavior prevents partial updates by default, there are cases where applying successful updates while reporting failures is desirable.

Add a new `--allow-partial` flag that allows the transaction to continue even when individual reference updates fail. This flag can only be used in `--stdin` mode and builds upon the partial transaction support added to the refs subsystem. When enabled, failed updates are reported in the following format:

  rejected SP (<old-oid> | <old-target>) SP (<new-oid> | <new-target>) SP <rejection-reason> LF
or with `-z`:
  rejected NUL (<old-oid> | <old-target>) NUL (<new-oid> | <new-target>) NUL <rejection-reason> NUL

Update the documentation to reflect this change and also tests to cover different scenarios where an update could be rejected.

Signed-off-by: Karthik Nayak <karthik.188@gmail.com>
---
 Documentation/git-update-ref.adoc |  21 +++-
 builtin/update-ref.c              |  74 +++++++++++--
 t/t1400-update-ref.sh             | 216 ++++++++++++++++++++++++++++++++++++++
 3 files changed, 302 insertions(+), 9 deletions(-)
Show changes to 3 files +302 −9

Documentation/git-update-ref.adoc, builtin/update-ref.c, t/t1400-update-ref.sh

diff --git a/Documentation/git-update-ref.adoc b/Documentation/git-update-ref.adoc
index 9e6935d38d..fc73f1d8aa 100644
--- a/Documentation/git-update-ref.adoc
+++ b/Documentation/git-update-ref.adoc
@@ -7,8 +7,10 @@ git-update-ref - Update the object name stored in a ref safely
 
 SYNOPSIS
 --------
-[verse]
-'git update-ref' [-m <reason>] [--no-deref] (-d <ref> [<old-oid>] | [--create-reflog] <ref> <new-oid> [<old-oid>] | --stdin [-z])
+[synopsis]
+git update-ref [-m <reason>] [--no-deref] -d <ref> [<old-oid>]
+	       [-m <reason>] [--no-deref] [--create-reflog] <ref> <new-oid> [<old-oid>]
+               [-m <reason>] [--no-deref] --stdin [-z] [--allow-partial]
 
 DESCRIPTION
 -----------
@@ -57,6 +59,17 @@ performs all modifications together.  Specify commands of the form:
 With `--create-reflog`, update-ref will create a reflog for each ref
 even if one would not ordinarily be created.
 
+With `--allow-partial`, update-ref continues executing the transaction even if
+some updates fail due to invalid or incorrect user input, applying only the
+successful updates. Errors resulting from user-provided input are treated as
+non-system-related and do not cause the entire transaction to be aborted.
+However, system-related errors—such as I/O failures or memory issues—will still
+result in a full failure. Additionally, errors like F/D conflicts are batched
+for performance optimization and will also cause a full failure. Any failed
+updates will be reported in the following format:
+
+	rejected SP (<old-oid> | <old-target>) SP (<new-oid> | <new-target>) SP <rejection-reason> LF
+
 Quote fields containing whitespace as if they were strings in C source
 code; i.e., surrounded by double-quotes and with backslash escapes.
 Use 40 "0" characters or the empty string to specify a zero value.  To
@@ -82,6 +95,10 @@ quoting:
 In this format, use 40 "0" to specify a zero value, and use the empty
 string to specify a missing value.
 
+With `-z`, `--allow-partial` will print rejections in the following form:
+
+	rejected NUL (<old-oid> | <old-target>) NUL (<new-oid> | <new-target>) NUL <rejection-reason> NUL
+
 In either format, values can be specified in any form that Git
 recognizes as an object name.  Commands in any other format or a
 repeated <ref> produce an error.  Command meanings are:
diff --git a/builtin/update-ref.c b/builtin/update-ref.c
index 1d541e13ad..b03b40eacb 100644
--- a/builtin/update-ref.c
+++ b/builtin/update-ref.c
@@ -5,6 +5,7 @@
 #include "config.h"
 #include "gettext.h"
 #include "hash.h"
+#include "hex.h"
 #include "refs.h"
 #include "object-name.h"
 #include "parse-options.h"
@@ -13,7 +14,7 @@
 static const char * const git_update_ref_usage[] = {
 	N_("git update-ref [<options>] -d <refname> [<old-oid>]"),
 	N_("git update-ref [<options>]    <refname> <new-oid> [<old-oid>]"),
-	N_("git update-ref [<options>] --stdin [-z]"),
+	N_("git update-ref [<options>] --stdin [-z] [--allow-partial]"),
 	NULL
 };
 
@@ -565,6 +566,54 @@ static void parse_cmd_abort(struct ref_transaction *transaction,
 	report_ok("abort");
 }
 
+static void print_rejected_refs(const char *refname,
+				const struct object_id *old_oid,
+				const struct object_id *new_oid,
+				const char *old_target,
+				const char *new_target,
+				enum transaction_error err,
+				void *cb_data UNUSED)
+{
+	struct strbuf sb = STRBUF_INIT;
+	char space = ' ';
+	const char *reason = "";
+
+	switch (err) {
+	case TRANSACTION_NAME_CONFLICT:
+		reason = _("refname conflict");
+		break;
+	case TRANSACTION_CREATE_EXISTS:
+		reason = _("reference already exists");
+		break;
+	case TRANSACTION_NONEXISTENT_REF:
+		reason = _("reference does not exist");
+		break;
+	case TRANSACTION_INCORRECT_OLD_VALUE:
+		reason = _("incorrect old value provided");
+		break;
+	case TRANSACTION_INVALID_NEW_VALUE:
+		reason = _("invalid new value provided");
+		break;
+	case TRANSACTION_EXPECTED_SYMREF:
+		reason = _("expected symref but found regular ref");
+		break;
+	default:
+		reason = _("unkown failure");
+	}
+
+	if (!line_termination)
+		space = line_termination;
+
+	strbuf_addf(&sb, "rejected%c%s%c%s%c%c%s%c%s%c", space,
+		    refname, space, new_oid ? oid_to_hex(new_oid) : new_target,
+		    space, space, old_oid ? oid_to_hex(old_oid) : old_target,
+		    space, reason, line_termination);
+
+	fwrite(sb.buf, sb.len, 1, stdout);
+	strbuf_release(&sb);
+	fflush(stdout);
+}
+
 static void parse_cmd_commit(struct ref_transaction *transaction,
 			     const char *next, const char *end UNUSED)
 {
@@ -573,6 +622,10 @@ static void parse_cmd_commit(struct ref_transaction *transaction,
 		die("commit: extra input: %s", next);
 	if (ref_transaction_commit(transaction, &error))
 		die("commit: %s", error.buf);
+
+	ref_transaction_for_each_rejected_update(transaction,
+						 print_rejected_refs, NULL);
+
 	report_ok("commit");
 	ref_transaction_free(transaction);
 }
@@ -609,7 +662,7 @@ static const struct parse_cmd {
 	{ "commit",        parse_cmd_commit,        0, UPDATE_REFS_CLOSED },
 };
 
-static void update_refs_stdin(void)
+static void update_refs_stdin(unsigned int flags)
 {
 	struct strbuf input = STRBUF_INIT, err = STRBUF_INIT;
 	enum update_refs_state state = UPDATE_REFS_OPEN;
@@ -617,7 +670,7 @@ static void update_refs_stdin(void)
 	int i, j;
 
 	transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
-						  0, &err);
+						  flags, &err);
 	if (!transaction)
 		die("%s", err.buf);
 
@@ -685,7 +738,7 @@ static void update_refs_stdin(void)
 			 */
 			state = cmd->state;
 			transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
-								  0, &err);
+								  flags, &err);
 			if (!transaction)
 				die("%s", err.buf);
 
@@ -701,6 +754,8 @@ static void update_refs_stdin(void)
 		/* Commit by default if no transaction was requested. */
 		if (ref_transaction_commit(transaction, &err))
 			die("%s", err.buf);
+		ref_transaction_for_each_rejected_update(transaction,
+						 print_rejected_refs, NULL);
 		ref_transaction_free(transaction);
 		break;
 	case UPDATE_REFS_STARTED:
@@ -726,7 +781,9 @@ int cmd_update_ref(int argc,
 	const char *refname, *oldval;
 	struct object_id oid, oldoid;
 	int delete = 0, no_deref = 0, read_stdin = 0, end_null = 0;
-	int create_reflog = 0;
+	int create_reflog = 0, allow_partial = 0;
+	unsigned int flags = 0;
+
 	struct option options[] = {
 		OPT_STRING( 'm', NULL, &msg, N_("reason"), N_("reason of the update")),
 		OPT_BOOL('d', NULL, &delete, N_("delete the reference")),
@@ -735,6 +792,8 @@ int cmd_update_ref(int argc,
 		OPT_BOOL('z', NULL, &end_null, N_("stdin has NUL-terminated arguments")),
 		OPT_BOOL( 0 , "stdin", &read_stdin, N_("read updates from stdin")),
 		OPT_BOOL( 0 , "create-reflog", &create_reflog, N_("create a reflog")),
+		OPT_BIT('0', "allow-partial", &flags, N_("allow partial transactions"),
+			REF_TRANSACTION_ALLOW_PARTIAL),
 		OPT_END(),
 	};
 
@@ -756,9 +815,10 @@ int cmd_update_ref(int argc,
 			usage_with_options(git_update_ref_usage, options);
 		if (end_null)
 			line_termination = '\0';
-		update_refs_stdin();
+		update_refs_stdin(flags);
 		return 0;
-	}
+	} else if (allow_partial)
+		die("--allow-partial can only be used with --stdin");
 
 	if (end_null)
 		usage_with_options(git_update_ref_usage, options);
diff --git a/t/t1400-update-ref.sh b/t/t1400-update-ref.sh
index 29045aad43..fb9442982e 100755
--- a/t/t1400-update-ref.sh
+++ b/t/t1400-update-ref.sh
@@ -2066,6 +2066,222 @@ do
 		grep "$(git rev-parse $a) $(git rev-parse $a)" actual
 	'
 
+	test_expect_success "stdin $type allow-partial" '
+		git init repo &&
+		test_when_finished "rm -fr repo" &&
+		(
+			cd repo &&
+			test_commit commit &&
+			head=$(git rev-parse HEAD) &&
+
+			format_command $type "update refs/heads/ref1" "$head" "$Z" >stdin &&
+			format_command $type "update refs/heads/ref2" "$head" "$Z" >>stdin &&
+			git update-ref $type --stdin --allow-partial <stdin &&
+			echo $head >expect &&
+			git rev-parse refs/heads/ref1 >actual &&
+			test_cmp expect actual &&
+			git rev-parse refs/heads/ref2 >actual &&
+			test_cmp expect actual
+		)
+	'
+
+	test_expect_success "stdin $type allow-partial with invalid new_oid" '
+		git init repo &&
+		test_when_finished "rm -fr repo" &&
+		(
+			cd repo &&
+			test_commit one &&
+			old_head=$(git rev-parse HEAD) &&
+			test_commit two &&
+			head=$(git rev-parse HEAD) &&
+			git update-ref refs/heads/ref1 $head &&
+			git update-ref refs/heads/ref2 $head &&
+
+			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
+			format_command $type "update refs/heads/ref2" "$(test_oid 001)" "$head" >>stdin &&
+			git update-ref $type --stdin --allow-partial <stdin >stdout &&
+			echo $old_head >expect &&
+			git rev-parse refs/heads/ref1 >actual &&
+			test_cmp expect actual &&
+			echo $head >expect &&
+			git rev-parse refs/heads/ref2 >actual &&
+			test_cmp expect actual &&
+			test_grep -q "invalid new value provided" stdout
+		)
+	'
+
+	test_expect_success "stdin $type allow-partial with non-commit new_oid" '
+		git init repo &&
+		test_when_finished "rm -fr repo" &&
+		(
+			cd repo &&
+			test_commit one &&
+			old_head=$(git rev-parse HEAD) &&
+			test_commit two &&
+			head=$(git rev-parse HEAD) &&
+			head_tree=$(git rev-parse HEAD^{tree}) &&
+			git update-ref refs/heads/ref1 $head &&
+			git update-ref refs/heads/ref2 $head &&
+
+			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
+			format_command $type "update refs/heads/ref2" "$head_tree" "$head" >>stdin &&
+			git update-ref $type --stdin --allow-partial <stdin >stdout &&
+			echo $old_head >expect &&
+			git rev-parse refs/heads/ref1 >actual &&
+			test_cmp expect actual &&
+			echo $head >expect &&
+			git rev-parse refs/heads/ref2 >actual &&
+			test_cmp expect actual &&
+			test_grep -q "invalid new value provided" stdout
+		)
+	'
+
+	test_expect_success "stdin $type allow-partial with non-existent ref" '
+		git init repo &&
+		test_when_finished "rm -fr repo" &&
+		(
+			cd repo &&
+			test_commit one &&
+			old_head=$(git rev-parse HEAD) &&
+			test_commit two &&
+			head=$(git rev-parse HEAD) &&
+			git update-ref refs/heads/ref1 $head &&
+
+			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
+			format_command $type "update refs/heads/ref2" "$old_head" "$head" >>stdin &&
+			git update-ref $type --stdin --allow-partial <stdin >stdout &&
+			echo $old_head >expect &&
+			git rev-parse refs/heads/ref1 >actual &&
+			test_cmp expect actual &&
+			test_must_fail git rev-parse refs/heads/ref2 &&
+			test_grep -q "reference does not exist" stdout
+		)
+	'
+
+	test_expect_success "stdin $type allow-partial with dangling symref" '
+		git init repo &&
+		test_when_finished "rm -fr repo" &&
+		(
+			cd repo &&
+			test_commit one &&
+			old_head=$(git rev-parse HEAD) &&
+			test_commit two &&
+			head=$(git rev-parse HEAD) &&
+			git update-ref refs/heads/ref1 $head &&
+			git symbolic-ref refs/heads/ref2 refs/heads/nonexistent &&
+
+			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
+			format_command $type "update refs/heads/ref2" "$old_head" "$head" >>stdin &&
+			git update-ref $type --no-deref --stdin --allow-partial <stdin >stdout &&
+			echo $old_head >expect &&
+			git rev-parse refs/heads/ref1 >actual &&
+			test_cmp expect actual &&
+			echo $head >expect &&
+			test_must_fail git rev-parse refs/heads/ref2 &&
+			test_grep -q "reference does not exist" stdout
+		)
+	'
+
+	test_expect_success "stdin $type allow-partial with regular ref as symref" '
+		git init repo &&
+		test_when_finished "rm -fr repo" &&
+		(
+			cd repo &&
+			test_commit one &&
+			old_head=$(git rev-parse HEAD) &&
+			test_commit two &&
+			head=$(git rev-parse HEAD) &&
+			git update-ref refs/heads/ref1 $head &&
+			git update-ref refs/heads/ref2 $head &&
+
+			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
+			format_command $type "symref-update refs/heads/ref2" "$old_head" "ref" "refs/heads/nonexistent" >>stdin &&
+			git update-ref $type --no-deref --stdin --allow-partial <stdin >stdout &&
+			echo $old_head >expect &&
+			git rev-parse refs/heads/ref1 >actual &&
+			test_cmp expect actual &&
+			echo $head >expect &&
+			echo $head >expect &&
+			git rev-parse refs/heads/ref2 >actual &&
+			test_cmp expect actual &&
+			test_grep -q "expected symref but found regular ref" stdout
+		)
+	'
+
+	test_expect_success "stdin $type allow-partial with invalid old_oid" '
+		git init repo &&
+		test_when_finished "rm -fr repo" &&
+		(
+			cd repo &&
+			test_commit one &&
+			old_head=$(git rev-parse HEAD) &&
+			test_commit two &&
+			head=$(git rev-parse HEAD) &&
+			git update-ref refs/heads/ref1 $head &&
+			git update-ref refs/heads/ref2 $head &&
+
+			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
+			format_command $type "update refs/heads/ref2" "$old_head" "$Z" >>stdin &&
+			git update-ref $type --stdin --allow-partial <stdin >stdout &&
+			echo $old_head >expect &&
+			git rev-parse refs/heads/ref1 >actual &&
+			test_cmp expect actual &&
+			echo $head >expect &&
+			git rev-parse refs/heads/ref2 >actual &&
+			test_cmp expect actual &&
+			test_grep -q "reference already exists" stdout
+		)
+	'
+
+	test_expect_success "stdin $type allow-partial with incorrect old oid" '
+		git init repo &&
+		test_when_finished "rm -fr repo" &&
+		(
+			cd repo &&
+			test_commit one &&
+			old_head=$(git rev-parse HEAD) &&
+			test_commit two &&
+			head=$(git rev-parse HEAD) &&
+			git update-ref refs/heads/ref1 $head &&
+			git update-ref refs/heads/ref2 $head &&
+
+			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
+			format_command $type "update refs/heads/ref2" "$head" "$old_head" >>stdin &&
+			git update-ref $type --stdin --allow-partial <stdin >stdout &&
+			echo $old_head >expect &&
+			git rev-parse refs/heads/ref1 >actual &&
+			test_cmp expect actual &&
+			echo $head >expect &&
+			git rev-parse refs/heads/ref2 >actual &&
+			test_cmp expect actual &&
+			test_grep -q "incorrect old value provided" stdout
+		)
+	'
+
+	# F/D conflicts on the files backend are resolved on an individual
+	# update level since refs are stored as files. On the reftable backend
+	# this check is batched to optimize for performance, so failures cannot
+	# be isolated to a single update.
+	test_expect_success REFFILES "stdin $type allow-partial refname conflict" '
+		git init repo &&
+		test_when_finished "rm -fr repo" &&
+		(
+			cd repo &&
+			test_commit one &&
+			old_head=$(git rev-parse HEAD) &&
+			test_commit two &&
+			head=$(git rev-parse HEAD) &&
+			git update-ref refs/heads/ref/foo $head &&
+
+			format_command $type "update refs/heads/ref/foo" "$old_head" "$head" >stdin &&
+			format_command $type "update refs/heads/ref" "$old_head" "" >>stdin &&
+			git update-ref $type --stdin --allow-partial <stdin >stdout &&
+			echo $old_head >expect &&
+			git rev-parse refs/heads/ref/foo >actual &&
+			test_cmp expect actual &&
+			test_grep -q "refname conflict" stdout
+		)
+	'
 done
 
 test_expect_success 'update-ref should also create reflog for HEAD' '
-- 
2.47.2
Patrick Steinhardt· Feb 25, 2025, 11:08 UTC · re: Karthik Nayak · lore

Re: [PATCH v2 7/7] update-ref: add --allow-partial flag for stdin mode

On Tue, Feb 25, 2025 at 10:29:10AM +0100, Karthik Nayak wrote:
Show 29 quoted lines
> diff --git a/Documentation/git-update-ref.adoc b/Documentation/git-update-ref.adoc
> index 9e6935d38d..fc73f1d8aa 100644
> --- a/Documentation/git-update-ref.adoc
> +++ b/Documentation/git-update-ref.adoc
> @@ -7,8 +7,10 @@ git-update-ref - Update the object name stored in a ref safely
>  
>  SYNOPSIS
>  --------
> -[verse]
> -'git update-ref' [-m <reason>] [--no-deref] (-d <ref> [<old-oid>] | [--create-reflog] <ref> <new-oid> [<old-oid>] | --stdin [-z])
> +[synopsis]
> +git update-ref [-m <reason>] [--no-deref] -d <ref> [<old-oid>]
> +	       [-m <reason>] [--no-deref] [--create-reflog] <ref> <new-oid> [<old-oid>]
> +               [-m <reason>] [--no-deref] --stdin [-z] [--allow-partial]
>  
>  DESCRIPTION
>  -----------
> @@ -57,6 +59,17 @@ performs all modifications together.  Specify commands of the form:
>  With `--create-reflog`, update-ref will create a reflog for each ref
>  even if one would not ordinarily be created.
>  
> +With `--allow-partial`, update-ref continues executing the transaction even if
> +some updates fail due to invalid or incorrect user input, applying only the
> +successful updates. Errors resulting from user-provided input are treated as
> +non-system-related and do not cause the entire transaction to be aborted.
> +However, system-related errors—such as I/O failures or memory issues—will still
> +result in a full failure. Additionally, errors like F/D conflicts are batched
> +for performance optimization and will also cause a full failure. Any failed
> +updates will be reported in the following format:

Shouldn't it be possible to detect F/D conflicts though and not abort the transaction? If we want to make use of partial transactions in the context of git-fetch(1) and/or git-receive-pack(1) we would have to handle them.

Show 42 quoted lines
> diff --git a/builtin/update-ref.c b/builtin/update-ref.c
> index 1d541e13ad..b03b40eacb 100644
> --- a/builtin/update-ref.c
> +++ b/builtin/update-ref.c
> @@ -565,6 +566,54 @@ static void parse_cmd_abort(struct ref_transaction *transaction,
>  	report_ok("abort");
>  }
>  
> +static void print_rejected_refs(const char *refname,
> +				const struct object_id *old_oid,
> +				const struct object_id *new_oid,
> +				const char *old_target,
> +				const char *new_target,
> +				enum transaction_error err,
> +				void *cb_data UNUSED)
> +{
> +	struct strbuf sb = STRBUF_INIT;
> +	char space = ' ';
> +	const char *reason = "";
> +
> +	switch (err) {
> +	case TRANSACTION_NAME_CONFLICT:
> +		reason = _("refname conflict");
> +		break;
> +	case TRANSACTION_CREATE_EXISTS:
> +		reason = _("reference already exists");
> +		break;
> +	case TRANSACTION_NONEXISTENT_REF:
> +		reason = _("reference does not exist");
> +		break;
> +	case TRANSACTION_INCORRECT_OLD_VALUE:
> +		reason = _("incorrect old value provided");
> +		break;
> +	case TRANSACTION_INVALID_NEW_VALUE:
> +		reason = _("invalid new value provided");
> +		break;
> +	case TRANSACTION_EXPECTED_SYMREF:
> +		reason = _("expected symref but found regular ref");
> +		break;
> +	default:
> +		reason = _("unkown failure");
> +	}

As git-update-ref(1) is part of plumbing we don't want to translate those messages.

Patrick
Karthik Nayak· Mar 3, 2025, 20:22 UTC · re: Patrick Steinhardt · lore

Re: [PATCH v2 7/7] update-ref: add --allow-partial flag for stdin mode

Patrick Steinhardt <ps@pks.im> writes:
Show 36 quoted lines
> On Tue, Feb 25, 2025 at 10:29:10AM +0100, Karthik Nayak wrote:
>> diff --git a/Documentation/git-update-ref.adoc b/Documentation/git-update-ref.adoc
>> index 9e6935d38d..fc73f1d8aa 100644
>> --- a/Documentation/git-update-ref.adoc
>> +++ b/Documentation/git-update-ref.adoc
>> @@ -7,8 +7,10 @@ git-update-ref - Update the object name stored in a ref safely
>>
>>  SYNOPSIS
>>  --------
>> -[verse]
>> -'git update-ref' [-m <reason>] [--no-deref] (-d <ref> [<old-oid>] | [--create-reflog] <ref> <new-oid> [<old-oid>] | --stdin [-z])
>> +[synopsis]
>> +git update-ref [-m <reason>] [--no-deref] -d <ref> [<old-oid>]
>> +	       [-m <reason>] [--no-deref] [--create-reflog] <ref> <new-oid> [<old-oid>]
>> +               [-m <reason>] [--no-deref] --stdin [-z] [--allow-partial]
>>
>>  DESCRIPTION
>>  -----------
>> @@ -57,6 +59,17 @@ performs all modifications together.  Specify commands of the form:
>>  With `--create-reflog`, update-ref will create a reflog for each ref
>>  even if one would not ordinarily be created.
>>
>> +With `--allow-partial`, update-ref continues executing the transaction even if
>> +some updates fail due to invalid or incorrect user input, applying only the
>> +successful updates. Errors resulting from user-provided input are treated as
>> +non-system-related and do not cause the entire transaction to be aborted.
>> +However, system-related errors—such as I/O failures or memory issues—will still
>> +result in a full failure. Additionally, errors like F/D conflicts are batched
>> +for performance optimization and will also cause a full failure. Any failed
>> +updates will be reported in the following format:
>
> Shouldn't it be possible to detect F/D conflicts though and not abort
> the transaction? If we want to make use of partial transactions in the
> context of git-fetch(1) and/or git-receive-pack(1) we would have to
> handle them.
>

Yes, this was a miss in this version, mostly from me not thinking enough about this series interacts with yours. This should be fixed in the next version.

Show 46 quoted lines
>> diff --git a/builtin/update-ref.c b/builtin/update-ref.c
>> index 1d541e13ad..b03b40eacb 100644
>> --- a/builtin/update-ref.c
>> +++ b/builtin/update-ref.c
>> @@ -565,6 +566,54 @@ static void parse_cmd_abort(struct ref_transaction *transaction,
>>  	report_ok("abort");
>>  }
>>
>> +static void print_rejected_refs(const char *refname,
>> +				const struct object_id *old_oid,
>> +				const struct object_id *new_oid,
>> +				const char *old_target,
>> +				const char *new_target,
>> +				enum transaction_error err,
>> +				void *cb_data UNUSED)
>> +{
>> +	struct strbuf sb = STRBUF_INIT;
>> +	char space = ' ';
>> +	const char *reason = "";
>> +
>> +	switch (err) {
>> +	case TRANSACTION_NAME_CONFLICT:
>> +		reason = _("refname conflict");
>> +		break;
>> +	case TRANSACTION_CREATE_EXISTS:
>> +		reason = _("reference already exists");
>> +		break;
>> +	case TRANSACTION_NONEXISTENT_REF:
>> +		reason = _("reference does not exist");
>> +		break;
>> +	case TRANSACTION_INCORRECT_OLD_VALUE:
>> +		reason = _("incorrect old value provided");
>> +		break;
>> +	case TRANSACTION_INVALID_NEW_VALUE:
>> +		reason = _("invalid new value provided");
>> +		break;
>> +	case TRANSACTION_EXPECTED_SYMREF:
>> +		reason = _("expected symref but found regular ref");
>> +		break;
>> +	default:
>> +		reason = _("unkown failure");
>> +	}
>
> As git-update-ref(1) is part of plumbing we don't want to translate
> those messages.
>
Makes sense, let me remove that.
> Patrick
>
Thanks for the review on the series!
Phillip Wood· Feb 25, 2025, 14:59 UTC · re: Karthik Nayak · lore

Re: [PATCH v2 7/7] update-ref: add --allow-partial flag for stdin mode

Hi Karthik
On 25/02/2025 09:29, Karthik Nayak wrote:
Show 10 quoted lines
> When updating multiple references through stdin, Git's update-ref
> command normally aborts the entire transaction if any single update
> fails. While this atomic behavior prevents partial updates by default,
> there are cases where applying successful updates while reporting
> failures is desirable.
> 
> Add a new `--allow-partial` flag that allows the transaction to continue
> even when individual reference updates fail. This flag can only be used
> in `--stdin` mode and builds upon the partial transaction support added
> to the refs subsystem.

As '--stdin' allows a single instance of "git update-ref" to create more than one transaction perhaps we should instead allow the caller to specify which transactions they want to allow to fail by passing an argument to "start", similar to how we support "no-deref" with "update"

Show 7 quoted lines
> following format:
> 
>    rejected SP (<old-oid> | <old-target>) SP (<new-oid> | <new-target>) SP <rejection-reason> LF
> 
> or with `-z`:
> 
>    rejected NUL (<old-oid> | <old-target>) NUL (<new-oid> | <new-target>) NUL <rejection-reason> NUL

What's the reason for the different output with '-z'? In the list of options '-z' is documented as only applying to the input stream. Looking at the code the existing messages generated by report_ok() are all printed to stdout with a LF terminator.

Show 34 quoted lines
> +static void print_rejected_refs(const char *refname,
> +				const struct object_id *old_oid,
> +				const struct object_id *new_oid,
> +				const char *old_target,
> +				const char *new_target,
> +				enum transaction_error err,
> +				void *cb_data UNUSED)
> +{
> +	struct strbuf sb = STRBUF_INIT;
> +	char space = ' ';
> +	const char *reason = "";
> +
> +	switch (err) {
> +	case TRANSACTION_NAME_CONFLICT:
> +		reason = _("refname conflict");
> +		break;
> +	case TRANSACTION_CREATE_EXISTS:
> +		reason = _("reference already exists");
> +		break;
> +	case TRANSACTION_NONEXISTENT_REF:
> +		reason = _("reference does not exist");
> +		break;
> +	case TRANSACTION_INCORRECT_OLD_VALUE:
> +		reason = _("incorrect old value provided");
> +		break;
> +	case TRANSACTION_INVALID_NEW_VALUE:
> +		reason = _("invalid new value provided");
> +		break;
> +	case TRANSACTION_EXPECTED_SYMREF:
> +		reason = _("expected symref but found regular ref");
> +		break;
> +	default:
> +		reason = _("unkown failure");
> +	}
I agree with Patrick that these messages should not be translated.
Show 11 quoted lines
> +	if (!line_termination)
> +		space = line_termination;
> +
> +	strbuf_addf(&sb, "rejected%c%s%c%s%c%c%s%c%s%c", space,
> +		    refname, space, new_oid ? oid_to_hex(new_oid) : new_target,
> +		    space, space, old_oid ? oid_to_hex(old_oid) : old_target,
> +		    space, reason, line_termination);
> +
> +	fwrite(sb.buf, sb.len, 1, stdout);
> +	strbuf_release(&sb);
> +	fflush(stdout);

There is no need to flush after each line, we'll flush all the error messages when we call report_ok() in parse_cmd_commit() or when the program exits. The caller has no way to know how many error messages there are to read so flushing each one individually does not help the reader avoid deadlocks.

Show 14 quoted lines
> +}
> +
>   static void parse_cmd_commit(struct ref_transaction *transaction,
>   			     const char *next, const char *end UNUSED)
>   {
> @@ -573,6 +622,10 @@ static void parse_cmd_commit(struct ref_transaction *transaction,
>   		die("commit: extra input: %s", next);
>   	if (ref_transaction_commit(transaction, &error))
>   		die("commit: %s", error.buf);
> +
> +	ref_transaction_for_each_rejected_update(transaction,
> +						 print_rejected_refs, NULL);
> +
>   	report_ok("commit");
This is good, the caller knows to stop reading when they see "commit: ok"
Best Wishes
Phillip
Show 299 quoted lines
>   	ref_transaction_free(transaction);
>   }
> @@ -609,7 +662,7 @@ static const struct parse_cmd {
>   	{ "commit",        parse_cmd_commit,        0, UPDATE_REFS_CLOSED },
>   };
>   
> -static void update_refs_stdin(void)
> +static void update_refs_stdin(unsigned int flags)
>   {
>   	struct strbuf input = STRBUF_INIT, err = STRBUF_INIT;
>   	enum update_refs_state state = UPDATE_REFS_OPEN;
> @@ -617,7 +670,7 @@ static void update_refs_stdin(void)
>   	int i, j;
>   
>   	transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
> -						  0, &err);
> +						  flags, &err);
>   	if (!transaction)
>   		die("%s", err.buf);
>   
> @@ -685,7 +738,7 @@ static void update_refs_stdin(void)
>   			 */
>   			state = cmd->state;
>   			transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
> -								  0, &err);
> +								  flags, &err);
>   			if (!transaction)
>   				die("%s", err.buf);
>   
> @@ -701,6 +754,8 @@ static void update_refs_stdin(void)
>   		/* Commit by default if no transaction was requested. */
>   		if (ref_transaction_commit(transaction, &err))
>   			die("%s", err.buf);
> +		ref_transaction_for_each_rejected_update(transaction,
> +						 print_rejected_refs, NULL);
>   		ref_transaction_free(transaction);
>   		break;
>   	case UPDATE_REFS_STARTED:
> @@ -726,7 +781,9 @@ int cmd_update_ref(int argc,
>   	const char *refname, *oldval;
>   	struct object_id oid, oldoid;
>   	int delete = 0, no_deref = 0, read_stdin = 0, end_null = 0;
> -	int create_reflog = 0;
> +	int create_reflog = 0, allow_partial = 0;
> +	unsigned int flags = 0;
> +
>   	struct option options[] = {
>   		OPT_STRING( 'm', NULL, &msg, N_("reason"), N_("reason of the update")),
>   		OPT_BOOL('d', NULL, &delete, N_("delete the reference")),
> @@ -735,6 +792,8 @@ int cmd_update_ref(int argc,
>   		OPT_BOOL('z', NULL, &end_null, N_("stdin has NUL-terminated arguments")),
>   		OPT_BOOL( 0 , "stdin", &read_stdin, N_("read updates from stdin")),
>   		OPT_BOOL( 0 , "create-reflog", &create_reflog, N_("create a reflog")),
> +		OPT_BIT('0', "allow-partial", &flags, N_("allow partial transactions"),
> +			REF_TRANSACTION_ALLOW_PARTIAL),
>   		OPT_END(),
>   	};
>   
> @@ -756,9 +815,10 @@ int cmd_update_ref(int argc,
>   			usage_with_options(git_update_ref_usage, options);
>   		if (end_null)
>   			line_termination = '\0';
> -		update_refs_stdin();
> +		update_refs_stdin(flags);
>   		return 0;
> -	}
> +	} else if (allow_partial)
> +		die("--allow-partial can only be used with --stdin");
>   
>   	if (end_null)
>   		usage_with_options(git_update_ref_usage, options);
> diff --git a/t/t1400-update-ref.sh b/t/t1400-update-ref.sh
> index 29045aad43..fb9442982e 100755
> --- a/t/t1400-update-ref.sh
> +++ b/t/t1400-update-ref.sh
> @@ -2066,6 +2066,222 @@ do
>   		grep "$(git rev-parse $a) $(git rev-parse $a)" actual
>   	'
>   
> +	test_expect_success "stdin $type allow-partial" '
> +		git init repo &&
> +		test_when_finished "rm -fr repo" &&
> +		(
> +			cd repo &&
> +			test_commit commit &&
> +			head=$(git rev-parse HEAD) &&
> +
> +			format_command $type "update refs/heads/ref1" "$head" "$Z" >stdin &&
> +			format_command $type "update refs/heads/ref2" "$head" "$Z" >>stdin &&
> +			git update-ref $type --stdin --allow-partial <stdin &&
> +			echo $head >expect &&
> +			git rev-parse refs/heads/ref1 >actual &&
> +			test_cmp expect actual &&
> +			git rev-parse refs/heads/ref2 >actual &&
> +			test_cmp expect actual
> +		)
> +	'
> +
> +	test_expect_success "stdin $type allow-partial with invalid new_oid" '
> +		git init repo &&
> +		test_when_finished "rm -fr repo" &&
> +		(
> +			cd repo &&
> +			test_commit one &&
> +			old_head=$(git rev-parse HEAD) &&
> +			test_commit two &&
> +			head=$(git rev-parse HEAD) &&
> +			git update-ref refs/heads/ref1 $head &&
> +			git update-ref refs/heads/ref2 $head &&
> +
> +			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
> +			format_command $type "update refs/heads/ref2" "$(test_oid 001)" "$head" >>stdin &&
> +			git update-ref $type --stdin --allow-partial <stdin >stdout &&
> +			echo $old_head >expect &&
> +			git rev-parse refs/heads/ref1 >actual &&
> +			test_cmp expect actual &&
> +			echo $head >expect &&
> +			git rev-parse refs/heads/ref2 >actual &&
> +			test_cmp expect actual &&
> +			test_grep -q "invalid new value provided" stdout
> +		)
> +	'
> +
> +	test_expect_success "stdin $type allow-partial with non-commit new_oid" '
> +		git init repo &&
> +		test_when_finished "rm -fr repo" &&
> +		(
> +			cd repo &&
> +			test_commit one &&
> +			old_head=$(git rev-parse HEAD) &&
> +			test_commit two &&
> +			head=$(git rev-parse HEAD) &&
> +			head_tree=$(git rev-parse HEAD^{tree}) &&
> +			git update-ref refs/heads/ref1 $head &&
> +			git update-ref refs/heads/ref2 $head &&
> +
> +			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
> +			format_command $type "update refs/heads/ref2" "$head_tree" "$head" >>stdin &&
> +			git update-ref $type --stdin --allow-partial <stdin >stdout &&
> +			echo $old_head >expect &&
> +			git rev-parse refs/heads/ref1 >actual &&
> +			test_cmp expect actual &&
> +			echo $head >expect &&
> +			git rev-parse refs/heads/ref2 >actual &&
> +			test_cmp expect actual &&
> +			test_grep -q "invalid new value provided" stdout
> +		)
> +	'
> +
> +	test_expect_success "stdin $type allow-partial with non-existent ref" '
> +		git init repo &&
> +		test_when_finished "rm -fr repo" &&
> +		(
> +			cd repo &&
> +			test_commit one &&
> +			old_head=$(git rev-parse HEAD) &&
> +			test_commit two &&
> +			head=$(git rev-parse HEAD) &&
> +			git update-ref refs/heads/ref1 $head &&
> +
> +			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
> +			format_command $type "update refs/heads/ref2" "$old_head" "$head" >>stdin &&
> +			git update-ref $type --stdin --allow-partial <stdin >stdout &&
> +			echo $old_head >expect &&
> +			git rev-parse refs/heads/ref1 >actual &&
> +			test_cmp expect actual &&
> +			test_must_fail git rev-parse refs/heads/ref2 &&
> +			test_grep -q "reference does not exist" stdout
> +		)
> +	'
> +
> +	test_expect_success "stdin $type allow-partial with dangling symref" '
> +		git init repo &&
> +		test_when_finished "rm -fr repo" &&
> +		(
> +			cd repo &&
> +			test_commit one &&
> +			old_head=$(git rev-parse HEAD) &&
> +			test_commit two &&
> +			head=$(git rev-parse HEAD) &&
> +			git update-ref refs/heads/ref1 $head &&
> +			git symbolic-ref refs/heads/ref2 refs/heads/nonexistent &&
> +
> +			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
> +			format_command $type "update refs/heads/ref2" "$old_head" "$head" >>stdin &&
> +			git update-ref $type --no-deref --stdin --allow-partial <stdin >stdout &&
> +			echo $old_head >expect &&
> +			git rev-parse refs/heads/ref1 >actual &&
> +			test_cmp expect actual &&
> +			echo $head >expect &&
> +			test_must_fail git rev-parse refs/heads/ref2 &&
> +			test_grep -q "reference does not exist" stdout
> +		)
> +	'
> +
> +	test_expect_success "stdin $type allow-partial with regular ref as symref" '
> +		git init repo &&
> +		test_when_finished "rm -fr repo" &&
> +		(
> +			cd repo &&
> +			test_commit one &&
> +			old_head=$(git rev-parse HEAD) &&
> +			test_commit two &&
> +			head=$(git rev-parse HEAD) &&
> +			git update-ref refs/heads/ref1 $head &&
> +			git update-ref refs/heads/ref2 $head &&
> +
> +			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
> +			format_command $type "symref-update refs/heads/ref2" "$old_head" "ref" "refs/heads/nonexistent" >>stdin &&
> +			git update-ref $type --no-deref --stdin --allow-partial <stdin >stdout &&
> +			echo $old_head >expect &&
> +			git rev-parse refs/heads/ref1 >actual &&
> +			test_cmp expect actual &&
> +			echo $head >expect &&
> +			echo $head >expect &&
> +			git rev-parse refs/heads/ref2 >actual &&
> +			test_cmp expect actual &&
> +			test_grep -q "expected symref but found regular ref" stdout
> +		)
> +	'
> +
> +	test_expect_success "stdin $type allow-partial with invalid old_oid" '
> +		git init repo &&
> +		test_when_finished "rm -fr repo" &&
> +		(
> +			cd repo &&
> +			test_commit one &&
> +			old_head=$(git rev-parse HEAD) &&
> +			test_commit two &&
> +			head=$(git rev-parse HEAD) &&
> +			git update-ref refs/heads/ref1 $head &&
> +			git update-ref refs/heads/ref2 $head &&
> +
> +			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
> +			format_command $type "update refs/heads/ref2" "$old_head" "$Z" >>stdin &&
> +			git update-ref $type --stdin --allow-partial <stdin >stdout &&
> +			echo $old_head >expect &&
> +			git rev-parse refs/heads/ref1 >actual &&
> +			test_cmp expect actual &&
> +			echo $head >expect &&
> +			git rev-parse refs/heads/ref2 >actual &&
> +			test_cmp expect actual &&
> +			test_grep -q "reference already exists" stdout
> +		)
> +	'
> +
> +	test_expect_success "stdin $type allow-partial with incorrect old oid" '
> +		git init repo &&
> +		test_when_finished "rm -fr repo" &&
> +		(
> +			cd repo &&
> +			test_commit one &&
> +			old_head=$(git rev-parse HEAD) &&
> +			test_commit two &&
> +			head=$(git rev-parse HEAD) &&
> +			git update-ref refs/heads/ref1 $head &&
> +			git update-ref refs/heads/ref2 $head &&
> +
> +			format_command $type "update refs/heads/ref1" "$old_head" "$head" >stdin &&
> +			format_command $type "update refs/heads/ref2" "$head" "$old_head" >>stdin &&
> +			git update-ref $type --stdin --allow-partial <stdin >stdout &&
> +			echo $old_head >expect &&
> +			git rev-parse refs/heads/ref1 >actual &&
> +			test_cmp expect actual &&
> +			echo $head >expect &&
> +			git rev-parse refs/heads/ref2 >actual &&
> +			test_cmp expect actual &&
> +			test_grep -q "incorrect old value provided" stdout
> +		)
> +	'
> +
> +	# F/D conflicts on the files backend are resolved on an individual
> +	# update level since refs are stored as files. On the reftable backend
> +	# this check is batched to optimize for performance, so failures cannot
> +	# be isolated to a single update.
> +	test_expect_success REFFILES "stdin $type allow-partial refname conflict" '
> +		git init repo &&
> +		test_when_finished "rm -fr repo" &&
> +		(
> +			cd repo &&
> +			test_commit one &&
> +			old_head=$(git rev-parse HEAD) &&
> +			test_commit two &&
> +			head=$(git rev-parse HEAD) &&
> +			git update-ref refs/heads/ref/foo $head &&
> +
> +			format_command $type "update refs/heads/ref/foo" "$old_head" "$head" >stdin &&
> +			format_command $type "update refs/heads/ref" "$old_head" "" >>stdin &&
> +			git update-ref $type --stdin --allow-partial <stdin >stdout &&
> +			echo $old_head >expect &&
> +			git rev-parse refs/heads/ref/foo >actual &&
> +			test_cmp expect actual &&
> +			test_grep -q "refname conflict" stdout
> +		)
> +	'
>   done
>   
>   test_expect_success 'update-ref should also create reflog for HEAD' '
> 
Karthik Nayak· Mar 3, 2025, 20:34 UTC · re: Phillip Wood · lore

Re: [PATCH v2 7/7] update-ref: add --allow-partial flag for stdin mode

Phillip Wood <phillip.wood123@gmail.com> writes:
Show 19 quoted lines
> Hi Karthik
>
> On 25/02/2025 09:29, Karthik Nayak wrote:
>> When updating multiple references through stdin, Git's update-ref
>> command normally aborts the entire transaction if any single update
>> fails. While this atomic behavior prevents partial updates by default,
>> there are cases where applying successful updates while reporting
>> failures is desirable.
>>
>> Add a new `--allow-partial` flag that allows the transaction to continue
>> even when individual reference updates fail. This flag can only be used
>> in `--stdin` mode and builds upon the partial transaction support added
>> to the refs subsystem.
>
> As '--stdin' allows a single instance of "git update-ref" to create more
> than one transaction perhaps we should instead allow the caller to
> specify which transactions they want to allow to fail by passing an
> argument to "start", similar to how we support "no-deref" with "update"
>

I was considering adding a 'allow-rejection' flag similar to "no-deref" with "update", but decided against it since that was an update level config and we want a transaction level configuration.

But I like your idea better. I'm not bullish on either the current implementation or your suggestion, since we can extend one from the other. My main motivation to add this flag to update-ref(1) is to show viability. The goal would be to follow up with changes to `git-fetch(1)` and `git-receive-pack(1)` to use partial transactions.

Show 13 quoted lines
>> following format:
>>
>>    rejected SP (<old-oid> | <old-target>) SP (<new-oid> | <new-target>) SP <rejection-reason> LF
>>
>> or with `-z`:
>>
>>    rejected NUL (<old-oid> | <old-target>) NUL (<new-oid> | <new-target>) NUL <rejection-reason> NUL
>
> What's the reason for the different output with '-z'? In the list of
> options '-z' is documented as only applying to the input stream. Looking
> at the code the existing messages generated by report_ok() are all
> printed to stdout with a LF terminator.
>

That's a great point, there was no real reason and I think we can drop this.

Show 55 quoted lines
>> +static void print_rejected_refs(const char *refname,
>> +				const struct object_id *old_oid,
>> +				const struct object_id *new_oid,
>> +				const char *old_target,
>> +				const char *new_target,
>> +				enum transaction_error err,
>> +				void *cb_data UNUSED)
>> +{
>> +	struct strbuf sb = STRBUF_INIT;
>> +	char space = ' ';
>> +	const char *reason = "";
>> +
>> +	switch (err) {
>> +	case TRANSACTION_NAME_CONFLICT:
>> +		reason = _("refname conflict");
>> +		break;
>> +	case TRANSACTION_CREATE_EXISTS:
>> +		reason = _("reference already exists");
>> +		break;
>> +	case TRANSACTION_NONEXISTENT_REF:
>> +		reason = _("reference does not exist");
>> +		break;
>> +	case TRANSACTION_INCORRECT_OLD_VALUE:
>> +		reason = _("incorrect old value provided");
>> +		break;
>> +	case TRANSACTION_INVALID_NEW_VALUE:
>> +		reason = _("invalid new value provided");
>> +		break;
>> +	case TRANSACTION_EXPECTED_SYMREF:
>> +		reason = _("expected symref but found regular ref");
>> +		break;
>> +	default:
>> +		reason = _("unkown failure");
>> +	}
>
> I agree with Patrick that these messages should not be translated.
>
>> +	if (!line_termination)
>> +		space = line_termination;
>> +
>> +	strbuf_addf(&sb, "rejected%c%s%c%s%c%c%s%c%s%c", space,
>> +		    refname, space, new_oid ? oid_to_hex(new_oid) : new_target,
>> +		    space, space, old_oid ? oid_to_hex(old_oid) : old_target,
>> +		    space, reason, line_termination);
>> +
>> +	fwrite(sb.buf, sb.len, 1, stdout);
>> +	strbuf_release(&sb);
>> +	fflush(stdout);
>
> There is no need to flush after each line, we'll flush all the error
> messages when we call report_ok() in parse_cmd_commit() or when the
> program exits. The caller has no way to know how many error messages
> there are to read so flushing each one individually does not help the
> reader avoid deadlocks.
>
That does make sense, I'll remove the flush here!
Show 21 quoted lines
>> +}
>> +
>>   static void parse_cmd_commit(struct ref_transaction *transaction,
>>   			     const char *next, const char *end UNUSED)
>>   {
>> @@ -573,6 +622,10 @@ static void parse_cmd_commit(struct ref_transaction *transaction,
>>   		die("commit: extra input: %s", next);
>>   	if (ref_transaction_commit(transaction, &error))
>>   		die("commit: %s", error.buf);
>> +
>> +	ref_transaction_for_each_rejected_update(transaction,
>> +						 print_rejected_refs, NULL);
>> +
>>   	report_ok("commit");
>
> This is good, the caller knows to stop reading when they see "commit: ok"
>
>
> Best Wishes
>
> Phillip
Thanks for the review on the series.

← back to recent threads