Skip to contentSkip to conversation

promise: introduce promises to track success or error

PATCH In review Philip Peterson via GitGitGadget 6 participants 13 messages Feb 18, 2024 – Mar 12, 2024 Kbuild

lore
Share & tools
lore
#0 lore raw

cover promise: introduce promises to track success or error

Hello all, this is my first patchset so thank you for being patient with me as I learn the process and conventions of your very fine project. These patches are intended as part of the Libification effort, to show how we could use a Promise structure to help return values from functions.

Problems
========

We seek to make libification easier by establishing a pattern for tracking whether a function errored in a rich way. Currently, any given function could immediately die(), or use error() to print directly to the console, bypassing any relevant verbosity checks. The use of die() currently makes use of Git as a library inconvenient since it is not graceful.

Additionally, returning using return error(...) (as is commonly done) always just returns a generic error value, -1, which provides little information.

Approach
========

I solve this problem by splitting the single return value into two return
values: error, and message. However, managing two output variables can require some coordination, and this coordination can be abstracted away by use of an existing pattern named Promise.

Promise Concept
===============

A promise is a contract representing "some task" that will eventually complete. Initially a promise is considered in a pending state. When it completes, one of two codepaths will eventually be entered: reject, or resolve. Once resolved or rejected, the promise enters a different state representing the result. Reject or resolve may only be called once on a given promise.

Until now, everything I described up to this point is consistent with other implementations, such as the ECMAScript standard for promises. However, this implementation departs from the complexity of those promises. In this implementation, promises are simple and canNOT be chained using .then(...) and do NOT have any notion of automatic bubbling (via re-entering the pending state).

Sample output and reproduction
==============================

During an error, we can have richer feedback as to what caused the problem.

% git apply garbage.patch
error:
could not find header
caused by:
patch fragment without header at line 1: @@ -2 +2 @@

To reproduce this output, you can use the following patch (garbage.patch):

@@ -2 +2 @@

Goals
=====

I would love to get feedback on this approach. This patchset is kept small, so as to serve as a minimal proof of concept. It is intended to abstract to asynchronous use-cases even though this is only a synchronous one. Eventually, any top-level function, such as apply_all_patches(...) would return its output via a promise to make the library interface as clean as possible, but this patchset does not accomplish this goal. Hopefully it can provide a direction to go in to achieve that.

Diversion
=========

While building this patchset, I noted a bug that may not have a concrete repro case in the master branch. The bug is that when invoking git am, it can call out to git apply, passing many flags but interestingly not the --quiet flag. I included a fix for this issue in the patchset.

Potential Issue
===============

There is one difficulty with this approach, which is the high level of repetition in the code required. Tracking which promise is which is its own source of complexity and may make mistakes more prone to happen. If anyone has suggestions for how to make the code cleaner, I would love to hear.

Thank you, Philip

Philip Peterson (5):
promise: add promise pattern to track success/error from operations
apply: use new promise structures in git-apply logic as a proving
ground
apply: update t4012 test suite
apply: pass through quiet flag to fix t4150
am: update test t4254 by adding the new error text

 Makefile               |   1 +
 apply.c                | 133 +++++++++++++++++++++++++++--------------
 apply.h                |   9 ++-
 builtin/am.c           |   5 ++
 promise.c              |  89 +++++++++++++++++++++++++++
 promise.h              |  71 ++++++++++++++++++++++
 range-diff.c           |  14 +++--
 t/t4012-diff-binary.sh |   4 +-
 t/t4254-am-corrupt.sh  |   9 ++-
 9 files changed, 279 insertions(+), 56 deletions(-)
 create mode 100644 promise.c
 create mode 100644 promise.h

base-commit: 2996f11c1d11ab68823f0939b6469dedc2b9ab90
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-1666%2Fphilip-peterson%2Fpeterson%2Femail-v1
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-1666/philip-peterson/peterson/email-v1
Pull-Request: https://github.com/git/git/pull/1666

Signature · 1 line
gitgitgadget
#1 lore raw

PATCH 1/5 promise: add promise pattern to track success/error from operations

From: Philip Peterson <[email protected]>

Introduce a promise paradigm. A promise starts off in the pending state, and represents an asynchronous (or synchronous) action that will eventually end in either a successful result or a failure result. If a failure result, an error message may be provided.

This allows us to represent tasks which may fail, while deferring any control flow actions or error printing that may occur in relation to said task.

---
 Makefile  |  1 +
 promise.c | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
 promise.h | 71 ++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 161 insertions(+)
 create mode 100644 promise.c
 create mode 100644 promise.h
Makefile +1 -0
index 78e874099d9..4851eb2d822 100644
@@ -1109,6 +1109,7 @@ LIB_OBJS += preload-index.o
 LIB_OBJS += pretty.o
 LIB_OBJS += prio-queue.o
 LIB_OBJS += progress.o
+LIB_OBJS += promise.o
 LIB_OBJS += promisor-remote.o
 LIB_OBJS += prompt.o
 LIB_OBJS += protocol.o
promise.c new file +89 -0

89 lines not on this page · raw message

promise.h new file +71 -0

71 lines not on this page · raw message

Signature · 1 line
gitgitgadget
#2 lore raw

PATCH 2/5 apply: use new promise structures in git-apply logic as a proving ground

In reply to Philip Peterson via GitGitGadget

From: Philip Peterson <[email protected]>

Uses the new promise paradigm in a simple example with git apply and git am. Several operations that may produce errors are encapsulated in a promise, so that any errors may be captured and handled according to how the caller wants to do so.

As an added bonus, we can see more context in error messages now, for example:

% git apply -3 garbage.patch
error:
could not find header
caused by:
no lines to read

---
 apply.c      | 133 +++++++++++++++++++++++++++++++++------------------
 apply.h      |   9 +++-
 range-diff.c |  14 ++++--
 3 files changed, 103 insertions(+), 53 deletions(-)
apply.c +87 -46
index 7608e3301ca..fb6b7074c19 100644
@@ -26,6 +26,7 @@
 #include "object-file.h"
 #include "parse-options.h"
 #include "path.h"
+#include "promise.h"
 #include "quote.h"
 #include "read-cache.h"
 #include "rerere.h"
@@ -1316,13 +1317,14 @@ static int check_header_line(int linenr, struct patch *patch)
 	return 0;
 }
 
-int parse_git_diff_header(struct strbuf *root,
+void parse_git_diff_header(struct strbuf *root,
 			  int *linenr,
 			  int p_value,
 			  const char *line,
 			  int len,
 			  unsigned int size,
-			  struct patch *patch)
+			  struct patch *patch,
+			  struct promise_t* return_promise)
 {
 	unsigned long offset;
 	struct gitdiff_data parse_hdr_state;
@@ -1386,10 +1388,12 @@ int parse_git_diff_header(struct strbuf *root,
 			if (len < oplen || memcmp(p->str, line, oplen))
 				continue;
 			res = p->fn(&parse_hdr_state, line + oplen, patch);
-			if (res < 0)
-				return -1;
-			if (check_header_line(*linenr, patch))
-				return -1;
+			if (res < 0) {
+				PROMISE_THROW(return_promise, APPLY_ERR_GENERIC, "operation for \"%s\" failed with code: %d", p->str, res);
+			}
+			if (check_header_line(*linenr, patch)) {
+				PROMISE_THROW(return_promise, APPLY_ERR_GENERIC, "invalid header lines");
+			}
 			if (res > 0)
 				goto done;
 			break;
@@ -1399,25 +1403,25 @@ int parse_git_diff_header(struct strbuf *root,
 done:
 	if (!patch->old_name && !patch->new_name) {
 		if (!patch->def_name) {
-			error(Q_("git diff header lacks filename information when removing "
-				 "%d leading pathname component (line %d)",
-				 "git diff header lacks filename information when removing "
-				 "%d leading pathname components (line %d)",
-				 parse_hdr_state.p_value),
-			      parse_hdr_state.p_value, *linenr);
-			return -128;
+			PROMISE_THROW(return_promise, -128,
+				Q_("git diff header lacks filename information when removing "
+					"%d leading pathname component (line %d)",
+					"git diff header lacks filename information when removing "
+					"%d leading pathname components (line %d)",
+					parse_hdr_state.p_value),
+					parse_hdr_state.p_value, *linenr
+			);
 		}
 		patch->old_name = xstrdup(patch->def_name);
 		patch->new_name = xstrdup(patch->def_name);
 	}
 	if ((!patch->new_name && !patch->is_delete) ||
 	    (!patch->old_name && !patch->is_new)) {
-		error(_("git diff header lacks filename information "
+		PROMISE_THROW(return_promise, -128, _("git diff header lacks filename information "
 			"(line %d)"), *linenr);
-		return -128;
 	}
 	patch->is_toplevel_relative = 1;
-	return offset;
+	PROMISE_SUCCEED(return_promise, offset);
 }
 
 static int parse_num(const char *line, unsigned long *p)
@@ -1539,16 +1543,17 @@ static int parse_fragment_header(const char *line, int len, struct fragment *fra
 /*
  * Find file diff header
  *
- * Returns:
+ * Resolves promise with:
  *  -1 if no header was found
  *  -128 in case of error
  *   the size of the header in bytes (called "offset") otherwise
  */
-static int find_header(struct apply_state *state,
+static void find_header(struct apply_state *state,
 		       const char *line,
 		       unsigned long size,
 		       int *hdrsize,
-		       struct patch *patch)
+		       struct patch *patch,
+			   struct promise_t* return_promise)
 {
 	unsigned long offset, len;
 
@@ -1577,9 +1582,8 @@ static int find_header(struct apply_state *state,
 			struct fragment dummy;
 			if (parse_fragment_header(line, len, &dummy) < 0)
 				continue;
-			error(_("patch fragment without header at line %d: %.*s"),
+			PROMISE_THROW(return_promise, -128, _("patch fragment without header at line %d: %.*s"),
 				     state->linenr, (int)len-1, line);
-			return -128;
 		}
 
 		if (size < len + 6)
@@ -1590,15 +1594,25 @@ static int find_header(struct apply_state *state,
 		 * or mode change, so we handle that specially
 		 */
 		if (!memcmp("diff --git ", line, 11)) {
-			int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
+			int git_hdr_len;
+			struct promise_t *parse_git_diff_header_promise = promise_init();
+			parse_git_diff_header(&state->root, &state->linenr,
 								state->p_value, line, len,
-								size, patch);
-			if (git_hdr_len < 0)
-				return -128;
+								size, patch, parse_git_diff_header_promise);
+			promise_assert_finished(parse_git_diff_header_promise);
+
+			if (parse_git_diff_header_promise->state == PROMISE_FAILURE) {
+				PROMISE_BUBBLE_UP(return_promise, parse_git_diff_header_promise,
+						 _("could not find file diff header"));
+			}
+
+			git_hdr_len = parse_git_diff_header_promise->result.success_result;
+			promise_release(parse_git_diff_header_promise);
 			if (git_hdr_len <= len)
 				continue;
 			*hdrsize = git_hdr_len;
-			return offset;
+			PROMISE_SUCCEED(return_promise, offset);
+			return;
 		}
 
 		/* --- followed by +++ ? */
@@ -1615,13 +1629,14 @@ static int find_header(struct apply_state *state,
 			continue;
 
 		/* Ok, we'll consider it a patch */
-		if (parse_traditional_patch(state, line, line+len, patch))
-			return -128;
+		if (parse_traditional_patch(state, line, line+len, patch)) {
+			PROMISE_THROW(return_promise, -128, "could not parse traditional patch");
+		}
 		*hdrsize = len + nextlen;
 		state->linenr += 2;
-		return offset;
+		PROMISE_SUCCEED(return_promise, offset);
 	}
-	return -1;
+	PROMISE_THROW(return_promise, APPLY_ERR_GENERIC, "no lines to read");
 }
 
 static void record_ws_error(struct apply_state *state,
@@ -2129,19 +2144,29 @@ static int use_patch(struct apply_state *state, struct patch *p)
  * reading after seeing a single patch (i.e. changes to a single file).
  * Create fragments (i.e. patch hunks) and hang them to the given patch.
  *
- * Returns:
+ * Resolves promise with:
  *   -1 if no header was found or parse_binary() failed,
  *   -128 on another error,
  *   the number of bytes consumed otherwise,
  *     so that the caller can call us again for the next patch.
  */
-static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
+static void parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch, struct promise_t* return_promise)
 {
-	int hdrsize, patchsize;
-	int offset = find_header(state, buffer, size, &hdrsize, patch);
+	int hdrsize = -1, patchsize, offset;
+	struct promise_t *find_header_promise = promise_init();
+	find_header(state, buffer, size, &hdrsize, patch, find_header_promise);
+	promise_assert_finished(find_header_promise);
 
-	if (offset < 0)
-		return offset;
+	if (find_header_promise->state == PROMISE_FAILURE) {
+		PROMISE_BUBBLE_UP(return_promise, find_header_promise, _("could not find header"));
+	}
+
+	offset = find_header_promise->result.success_result;
+	promise_release(find_header_promise);
+
+	if (offset < 0) {
+		PROMISE_SUCCEED(return_promise, offset);
+	}
 
 	prefix_patch(state, patch);
 
@@ -2159,8 +2184,9 @@ static int parse_chunk(struct apply_state *state, char *buffer, unsigned long si
 				       size - offset - hdrsize,
 				       patch);
 
-	if (patchsize < 0)
-		return -128;
+	if (patchsize < 0) {
+		PROMISE_THROW(return_promise, -128, _("could not parse patch"));
+	}
 
 	if (!patchsize) {
 		static const char git_binary[] = "GIT binary patch\n";
@@ -2173,8 +2199,9 @@ static int parse_chunk(struct apply_state *state, char *buffer, unsigned long si
 			state->linenr++;
 			used = parse_binary(state, buffer + hd + llen,
 					    size - hd - llen, patch);
-			if (used < 0)
-				return -1;
+			if (used < 0) {
+				PROMISE_THROW(return_promise, -1, _("could not parse binary patch"));
+			}
 			if (used)
 				patchsize = used + llen;
 			else
@@ -2205,12 +2232,11 @@ static int parse_chunk(struct apply_state *state, char *buffer, unsigned long si
 		 */
 		if ((state->apply || state->check) &&
 		    (!patch->is_binary && !metadata_changes(patch))) {
-			error(_("patch with only garbage at line %d"), state->linenr);
-			return -128;
+			PROMISE_THROW(return_promise, -128, _("patch with only garbage at line %d"), state->linenr);
 		}
 	}
 
-	return offset + hdrsize + patchsize;
+	PROMISE_SUCCEED(return_promise, offset + hdrsize + patchsize);
 }
 
 static void reverse_patches(struct patch *p)
@@ -4755,21 +4781,36 @@ static int apply_patch(struct apply_state *state,
 		return -128;
 	offset = 0;
 	while (offset < buf.len) {
-		struct patch *patch;
 		int nr;
+		struct patch *patch;
+		struct promise_t *parse_chunk_promise;
 
 		CALLOC_ARRAY(patch, 1);
 		patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
 		patch->recount =  !!(options & APPLY_OPT_RECOUNT);
-		nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
-		if (nr < 0) {
+
+		parse_chunk_promise = promise_init();
+		parse_chunk(state, buf.buf + offset, buf.len - offset, patch, parse_chunk_promise);
+
+		promise_assert_finished(parse_chunk_promise);
+
+		if (parse_chunk_promise->state == PROMISE_FAILURE) {
+			int nr;
+			nr = parse_chunk_promise->result.failure_result.status;
 			free_patch(patch);
 			if (nr == -128) {
+				error("\n\t%s", parse_chunk_promise->result.failure_result.message.buf);
+				promise_release(parse_chunk_promise);
 				res = -128;
 				goto end;
 			}
+			promise_release(parse_chunk_promise);
 			break;
 		}
+
+		nr = parse_chunk_promise->result.success_result;
+		promise_release(parse_chunk_promise);
+
 		if (state->apply_in_reverse)
 			reverse_patches(patch);
 		if (use_patch(state, patch)) {
apply.h +7 -2
index 7cd38b1443c..44af75883c5 100644
@@ -5,6 +5,10 @@
 #include "lockfile.h"
 #include "string-list.h"
 #include "strmap.h"
+#include "promise.h"
+
+/* Error codes (must be less than 0) */
+#define APPLY_ERR_GENERIC -1
 
 struct repository;
 
@@ -165,13 +169,14 @@ int check_apply_state(struct apply_state *state, int force_apply);
  *
  * Returns -1 on failure, the length of the parsed header otherwise.
  */
-int parse_git_diff_header(struct strbuf *root,
+void parse_git_diff_header(struct strbuf *root,
 			  int *linenr,
 			  int p_value,
 			  const char *line,
 			  int len,
 			  unsigned int size,
-			  struct patch *patch);
+			  struct patch *patch,
+			  struct promise_t *promise);
 
 void release_patch(struct patch *patch);
 
range-diff.c +9 -5
index c45b6d849cb..3ef8b976a0c 100644
@@ -121,8 +121,8 @@ static int read_patches(const char *range, struct string_list *list,
 		if (starts_with(line, "diff --git")) {
 			struct patch patch = { 0 };
 			struct strbuf root = STRBUF_INIT;
+			struct promise_t *parse_git_diff_header_promise = promise_init();
 			int linenr = 0;
-			int orig_len;
 
 			in_header = 0;
 			strbuf_addch(&buf, '\n');
@@ -130,16 +130,20 @@ static int read_patches(const char *range, struct string_list *list,
 				util->diff_offset = buf.len;
 			if (eol)
 				*eol = '\n';
-			orig_len = len;
-			len = parse_git_diff_header(&root, &linenr, 0, line,
-						    len, size, &patch);
-			if (len < 0) {
+			parse_git_diff_header(&root, &linenr, 0, line,
+						    len, size, &patch, parse_git_diff_header_promise);
+			promise_assert_finished(parse_git_diff_header_promise);
+			if (parse_git_diff_header_promise->state == PROMISE_FAILURE) {
+				int orig_len = len;
 				error(_("could not parse git header '%.*s'"),
 				      orig_len, line);
 				FREE_AND_NULL(util);
 				string_list_clear(list, 1);
+				promise_release(parse_git_diff_header_promise);
 				goto cleanup;
 			}
+			len = parse_git_diff_header_promise->result.success_result;
+			promise_release(parse_git_diff_header_promise);
 			strbuf_addstr(&buf, " ## ");
 			if (patch.is_new > 0)
 				strbuf_addf(&buf, "%s (new)", patch.new_name);
Signature · 1 line
gitgitgadget
#3 lore raw

PATCH 3/5 apply: update t4012 test suite

In reply to Philip Peterson via GitGitGadget

From: Philip Peterson <[email protected]>

The test suite matched against a regex that expected the entire errored output to end before the additional context added to git apply.

---
 t/t4012-diff-binary.sh | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
t/t4012-diff-binary.sh +2 -2
index c64d9d2f405..59defaa37b8 100755
@@ -68,7 +68,7 @@ test_expect_success 'apply detecting corrupt patch correctly' '
 	git diff >output &&
 	sed -e "s/-CIT/xCIT/" <output >broken &&
 	test_must_fail git apply --stat --summary broken 2>detected &&
-	detected=$(cat detected) &&
+	detected=$(head -n 1 detected) &&
 	detected=$(expr "$detected" : "error.*at line \\([0-9]*\\)\$") &&
 	detected=$(sed -ne "${detected}p" broken) &&
 	test "$detected" = xCIT
@@ -77,7 +77,7 @@ test_expect_success 'apply detecting corrupt patch correctly' '
 test_expect_success 'apply detecting corrupt patch correctly' '
 	git diff --binary | sed -e "s/-CIT/xCIT/" >broken &&
 	test_must_fail git apply --stat --summary broken 2>detected &&
-	detected=$(cat detected) &&
+	detected=$(head -n 1 detected) &&
 	detected=$(expr "$detected" : "error.*at line \\([0-9]*\\)\$") &&
 	detected=$(sed -ne "${detected}p" broken) &&
 	test "$detected" = xCIT
Signature · 1 line
gitgitgadget
#4 lore raw

PATCH 4/5 apply: pass through quiet flag to fix t4150

In reply to Philip Peterson via GitGitGadget

From: Philip Peterson <[email protected]>

This test was failing because it expects the invocation of git apply to be silent. Because previous patches introduce verbosity where previously there was a silent error (in the form of a return code), this adds an opportunity for a bug to become visible. The bug is in the way git am invokes git apply, not passing through --quiet when it is specified.

---
 builtin/am.c | 5 +++++
 1 file changed, 5 insertions(+)
builtin/am.c +5 -0
index d1990d7edcb..799cb8128a3 100644
@@ -36,6 +36,7 @@
 #include "mailinfo.h"
 #include "apply.h"
 #include "string-list.h"
+#include "packfile.h"
 #include "pager.h"
 #include "path.h"
 #include "repository.h"
@@ -2412,6 +2413,10 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 
 	argc = parse_options(argc, argv, prefix, options, usage, 0);
 
+	if (state.quiet) {
+		strvec_push(&state.git_apply_opts, "--quiet");
+	}
+
 	if (binary >= 0)
 		fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
 				"it will be removed. Please do not use it anymore."));
Signature · 1 line
gitgitgadget
#5 lore raw

PATCH 5/5 am: update test t4254 by adding the new error text

In reply to Philip Peterson via GitGitGadget

From: Philip Peterson <[email protected]>

The old error text was shorter than the new, so this just adds the new context message to the expected text.

---
 t/t4254-am-corrupt.sh | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
t/t4254-am-corrupt.sh +8 -1
index 45f1d4f95e5..265bcc41bbd 100755
@@ -60,7 +60,14 @@ test_expect_success setup '
 test_expect_success 'try to apply corrupted patch' '
 	test_when_finished "git am --abort" &&
 	test_must_fail git -c advice.amWorkDir=false am bad-patch.diff 2>actual &&
-	echo "error: git diff header lacks filename information (line 4)" >expected &&
+	space=" " &&
+	echo \
+"error:$space
+	could not find header
+caused by:
+	could not find file diff header
+caused by:
+	git diff header lacks filename information (line 4)" >expected &&
 	test_path_is_file f &&
 	test_cmp expected actual
 '
Signature · 1 line
gitgitgadget
#6 lore raw
In reply to Philip Peterson via GitGitGadget

Hi Philip

Quoted 4 lines · Philip Peterson via GitGitGadget

Hello all, this is my first patchset so thank you for being patient with me as I learn the process and conventions of your very fine project. These patches are intended as part of the Libification effort, to show how we could use a Promise structure to help return values from functions.

I agree that we could do with a better way of propagating errors ups the call-chain that (a) allows us to pass more detailed information about the error to the caller and (b) add useful context to the error message as the stack in unwound. I'm afraid I do not think that the promise implementation in this patch series is a good way forward for several reasons.

1) It is hard to see how we can wrap the return value of the function in a promise and preserve type safety. Even if we used some kind of union the compiler will not warn us if the caller reads a different member to the one that the callee set.

2) It obscures the return type of the function and forces callers to unpack the value from the promise adding complexity to the calling code.

3) It imposes a cost in terms of dynamic memory allocation on code that is called synchronously and therefore does not need to allocate the promise on the heap. This adds complexity and is sure to result in memory leaks.

4) If the function fails we need to propagate the error using PROMISE_BUBBLE_UP() which forces the caller to add more context to the error message even if it does covey anything useful to the user. For example in patch 5 we see

error:
could not find header
caused by:
could not find file diff header
caused by:
git diff header lacks filename information (line 4)" >expected

The error message starts by saying it couldn't find the header and ends by saying it did actually find the header but it could not parse it.

5) The cover letter talks about adding asynchronous examples in the future but it is not clear what part of the git code base it is referring to.

I think we'd be better served by some kind of structured error type like the failure_result in this patch series that is allocated on the stack by the caller at the entry point to the library and passed down the call chain. That avoids the need for lots of dynamic allocations and allows us to continue allocating "out" parameters on the stack. For example

    int f(struct repository *r) {
	struct object_id oid;

	if (repo_get_oid(r, "HEAD", &oid))
		return error(_("could not parse HEAD"))

	/* use oid here */
    }

would become

    int f(struct repository *r, struct error *err) {
	struct object_id oid;

	if (repo_get_oid(r, "HEAD", &oid))
		return error(&err, _("could not parse HEAD"))

	/* use oid here */
    }

I'm sure this has been discussed in the past but I didn't manage to turn anything up with a quick search of the archive on lore.kernel.org.

Best Wishes

Phillip

Quoted 115 lines

Problems
========

We seek to make libification easier by establishing a pattern for tracking whether a function errored in a rich way. Currently, any given function could immediately die(), or use error() to print directly to the console, bypassing any relevant verbosity checks. The use of die() currently makes use of Git as a library inconvenient since it is not graceful.

Additionally, returning using return error(...) (as is commonly done) always just returns a generic error value, -1, which provides little information.

Approach
========

I solve this problem by splitting the single return value into two return
values: error, and message. However, managing two output variables can require some coordination, and this coordination can be abstracted away by use of an existing pattern named Promise.

Promise Concept
===============

A promise is a contract representing "some task" that will eventually complete. Initially a promise is considered in a pending state. When it completes, one of two codepaths will eventually be entered: reject, or resolve. Once resolved or rejected, the promise enters a different state representing the result. Reject or resolve may only be called once on a given promise.

Until now, everything I described up to this point is consistent with other implementations, such as the ECMAScript standard for promises. However, this implementation departs from the complexity of those promises. In this implementation, promises are simple and canNOT be chained using .then(...) and do NOT have any notion of automatic bubbling (via re-entering the pending state).

Sample output and reproduction
==============================

During an error, we can have richer feedback as to what caused the problem.

% git apply garbage.patch
error:
could not find header
caused by:
patch fragment without header at line 1: @@ -2 +2 @@

To reproduce this output, you can use the following patch (garbage.patch):

(quoted diff) +0 -0
@@ -2 +2 @@
 

Goals
=====

I would love to get feedback on this approach. This patchset is kept small, so as to serve as a minimal proof of concept. It is intended to abstract to asynchronous use-cases even though this is only a synchronous one. Eventually, any top-level function, such as apply_all_patches(...) would return its output via a promise to make the library interface as clean as possible, but this patchset does not accomplish this goal. Hopefully it can provide a direction to go in to achieve that.

Diversion
=========

While building this patchset, I noted a bug that may not have a concrete repro case in the master branch. The bug is that when invoking git am, it can call out to git apply, passing many flags but interestingly not the --quiet flag. I included a fix for this issue in the patchset.

Potential Issue
===============

There is one difficulty with this approach, which is the high level of repetition in the code required. Tracking which promise is which is its own source of complexity and may make mistakes more prone to happen. If anyone has suggestions for how to make the code cleaner, I would love to hear.

Thank you, Philip

Philip Peterson (5):
promise: add promise pattern to track success/error from operations
apply: use new promise structures in git-apply logic as a proving
ground
apply: update t4012 test suite
apply: pass through quiet flag to fix t4150
am: update test t4254 by adding the new error text

  Makefile               |   1 +
  apply.c                | 133 +++++++++++++++++++++++++++--------------
  apply.h                |   9 ++-
  builtin/am.c           |   5 ++
  promise.c              |  89 +++++++++++++++++++++++++++
  promise.h              |  71 ++++++++++++++++++++++
  range-diff.c           |  14 +++--
  t/t4012-diff-binary.sh |   4 +-
  t/t4254-am-corrupt.sh  |   9 ++-
  9 files changed, 279 insertions(+), 56 deletions(-)

create mode 100644 promise.c
create mode 100644 promise.h

base-commit: 2996f11c1d11ab68823f0939b6469dedc2b9ab90
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-1666%2Fphilip-peterson%2Fpeterson%2Femail-v1
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-1666/philip-peterson/peterson/email-v1
Pull-Request: https://github.com/git/git/pull/1666

#7 lore raw
Quoted 25 lines · Phillip Wood

I think we'd be better served by some kind of structured error type like the failure_result in this patch series that is allocated on the stack by the caller at the entry point to the library and passed down the call chain. That avoids the need for lots of dynamic allocations and allows us to continue allocating "out" parameters on the stack. For example

    int f(struct repository *r) {
	struct object_id oid;

	if (repo_get_oid(r, "HEAD", &oid))
		return error(_("could not parse HEAD"))

	/* use oid here */
    }

would become

    int f(struct repository *r, struct error *err) {
	struct object_id oid;

	if (repo_get_oid(r, "HEAD", &oid))
		return error(&err, _("could not parse HEAD"))

	/* use oid here */
    }
Quoted 2 lines

I'm sure this has been discussed in the past but I didn't manage to turn anything up with a quick search of the archive on lore.kernel.org.

There's some discussion in this sub-thread:

https://lore.kernel.org/git/[email protected]/

that also references this earlier thread:

https://lore.kernel.org/git/[email protected]/

I still think this is a reasonable way to go. At one point I had a proof-of-concept conversion of some of the ref code, but I don't think I have it any more.

-Peff

#8 lore raw

Hi Peff

Quoted 5 lines · Jeff King
Quoted 2 lines · Phillip Wood

I'm sure this has been discussed in the past but I didn't manage to turn anything up with a quick search of the archive on lore.kernel.org.

Quoted 7 lines

There's some discussion in this sub-thread:

   https://lore.kernel.org/git/[email protected]/

that also references this earlier thread:

   https://lore.kernel.org/git/[email protected]/

Thanks for digging up those links

Quoted 3 lines

I still think this is a reasonable way to go. At one point I had a proof-of-concept conversion of some of the ref code, but I don't think I have it any more.

Ah, that's interesting - the ref transaction functions already take a struct strbuf to populate with an error message so maybe that would be a simple place to start with a conversion to an error struct.

Best Wishes

Phillip

#9 lore raw
Quoted 18 lines · Phillip Wood

Hi Peff

Quoted 5 lines · Jeff King
Quoted 2 lines · Phillip Wood

I'm sure this has been discussed in the past but I didn't manage to turn anything up with a quick search of the archive on lore.kernel.org.

Quoted 7 lines

There's some discussion in this sub-thread:

   https://lore.kernel.org/git/[email protected]/

that also references this earlier thread:

   https://lore.kernel.org/git/[email protected]/

Thanks for digging up those links

Quoted 7 lines
Quoted 3 lines

I still think this is a reasonable way to go. At one point I had a proof-of-concept conversion of some of the ref code, but I don't think I have it any more.

Ah, that's interesting - the ref transaction functions already take a struct strbuf to populate with an error message so maybe that would be a simple place to start with a conversion to an error struct.

I would certainly welcome such a change. It might make sense to wait a bit until the reftable dust has settled, but once that code has landed I'd be quite happy to see improvements to our error handling.

While we're already at it throwing ideas around, I also have to wonder whether this would be a long-term solution towards computer-friendly errors. One of the problems we quite frequently hit in Gitaly is that we are forced to parse error messages in order to figure out why exactly something has failed. Needless to say, this is quite fragile and also feels very wrong.

Now if we had a more structured way to pass errors around this might also enable us to convey more meaning to the caller of Git commands. In a hypothetical world where all errors were using an explicit error type, then this error type could eventually become richer and contain more information that is relevant to the calling script. And if such rich error information was available, then it would not be that far fetched to ask Git to emit errors in a computer-parsable format like for example JSON.

Patrick

#10 lore raw
Quoted 7 lines · Patrick Steinhardt

While we're already at it throwing ideas around, I also have to wonder whether this would be a long-term solution towards computer-friendly errors. One of the problems we quite frequently hit in Gitaly is that we are forced to parse error messages in order to figure out why exactly something has failed. Needless to say, this is quite fragile and also feels very wrong.

Quoted 8 lines

Now if we had a more structured way to pass errors around this might also enable us to convey more meaning to the caller of Git commands. In a hypothetical world where all errors were using an explicit error type, then this error type could eventually become richer and contain more information that is relevant to the calling script. And if such rich error information was available, then it would not be that far fetched to ask Git to emit errors in a computer-parsable format like for example JSON.

I do not know about the "JSON-parseable" part, but a structured error message, or even just a set of error codes that can be recorded in an index, might already be a great improvement.

#11 lore raw
In reply to Patrick Steinhardt
Quoted 7 lines · Patrick Steinhardt

While we're already at it throwing ideas around, I also have to wonder whether this would be a long-term solution towards computer-friendly errors. One of the problems we quite frequently hit in Gitaly is that we are forced to parse error messages in order to figure out why exactly something has failed. Needless to say, this is quite fragile and also feels very wrong.

Quoted 8 lines

Now if we had a more structured way to pass errors around this might also enable us to convey more meaning to the caller of Git commands. In a hypothetical world where all errors were using an explicit error type, then this error type could eventually become richer and contain more information that is relevant to the calling script. And if such rich error information was available, then it would not be that far fetched to ask Git to emit errors in a computer-parsable format like for example JSON.

I think what I'm proposing (and if I understand correctly what Phillip was thinking) is somewhat orthogonal. I agree that structured errors are nice for computers to read. But it does open up a pretty big can of worms regarding classifying each error, especially as root causes are often multi-level.

For example, imagine that the caller asks to resolve a ref. We might get a syscall error opening the loose ref. Or we might get one opening the packed-refs file (in a reftable world, you might imagine errors opening various other files). What is the structured error? Obviously it is "we can't resolve that ref" at some level. But the caller might want to know about the failed open (whether it is just ENOENT, or if we ran into EPERM or even EIO).

Or looking at higher levels; if I ask for the merge base between A and B, but one of those can't be resolved, how do we communicate that error? It is some sort of "cannot resolve" error, but it needs to be parameterized to know which is which.

All of those questions can be answered, of course, but now we are developing a micro-format that lets us describe all errors in a standardized way. And I think that is going to put a burden on the code which is generating the errors (and potentially on the consumers, too, if they have to decipher the structure to figure out what they want).

Whereas what I was really advocating for is punting on the structured thing entirely. We keep our unstructured string errors for the most part, but we simply let the caller pass in a context that tells us what to do with them. That lets us keep providing specific error messages from low-level functions without printing to stderr or exiting, which higher-level code (especially lib-ified code) would not want.

I think it could also be the first building block for making more structured errors (since those low-level callers are free to provide lots of details), but it doesn't have to be.

-Peff

#12 lore raw

Hi all,

Thanks for the feedback. Reading between the lines, it sounds like we are not quite happy with the flavor of the approach. To deconstruct, so we can evaluate each axis:

1. Canonical indication of pass/fail (as opposed to implicit rules about return value being negative or positive or nonzero indicating failure)

2. Coupling of control flow with result reporting Bubble-up functionality - Essentially a convention for handling die()-like functionality without calling die() and ending the process

3. Further error context via breadcrumbs (Foo errored because Bar errored because Baz errored)

4. Error codes - Rather than just -1, having a richer, named space of errors

5. Rich error data - void *data attached to each error (not actually proposed as part of promise but may be relevant)

6. Async-capable - shelving this since it may require further justification.

First, bubble-up functionality (#3) seems like it will be critical to support if we intend to stop calling die(). This can be done either exhaustively (by manually checking each error to see if it is fatal, and if so, invoking a control-flow action), or by a macro. I couldn’t find any established conventions for doing this in C, and the original patch series doesn’t really address this well either since it requires a manual if (...) check, so it is an area for further exploration. (Actually another proposed alternative was longjmp, but it sounds like that is a can of worms to be avoided.)

Back to the overall approach. To contrast to one alternative, error reporting functions a la the intriguing thread by Peff:

https://lore.kernel.org/git/[email protected]/

With that pattern, there is no concept of an overall status, either pass or fail. One must assume that if there was an error, then the operation failed, and if no error, then it passed. But then there is a question of whether an error was fatal. We know that some errors are fatal (meaning an immediate halt of execution is in order) and others are not. If we implemented this approach we would probably need to add this bool is_fatal as a field to struct error_context.

Also, unless a macro is employed, the reporting of errors is not coupled with control flow (#2) unlike promise, since PROMISE_THROW() invokes a return statement. Of course, Peff’s code there was just a sketch instead of a full-blown patch, but not coupling the two could easily lead to bugs in the form of accidentally-omitted return statements, so perhaps a macro is in order if that pattern is implemented.

The lifecycle of anything in void *data poses its own challenges. While promise offers macros to handle the strbuf release at EOL, special handlers would need to be written to free anything stored in void *data. Which brings me to this feedback:

Quoted 7 lines

1) It is hard to see how we can wrap the return value of the function in a promise and preserve type safety. Even if we used some kind of union the compiler will not warn us if the caller reads a different member to the one that the callee set.

2) It obscures the return type of the function and forces callers to unpack the value from the promise adding complexity to the calling code.

I should clarify that the promise concept is not intended to expand in scope as far as the return value. It should remain as int and only ever int, so no return value would be anything other than a simple number, meaning AFAIK (1) should not apply. For (2), if auxiliary data structures (additional ints, or structs, etc.) are outputs, they would need to be via "output parameters" passed into the function. Those output parameters should not need to be unpacked, since their type is preserved in the normal way.

However to return to void *data in struct error_context, the unpacking *would* be necessary since *data doesn’t have a concrete type. Therefore, if we go with struct error_context, the *data field should be omitted since it adds complexity without need.

Since we are dropping async support, I am going to rename the topic from Promise to Result as well, since the idea is equivalent to Result<T, E> in Rust, aka Either a b in Haskell.

Regarding error messages, totally valid criticism that they are confusing to the user as posed in the original patchset. Eventually perhaps the messages could be reworded to increase clarity, but to avoid scope creep, let’s just not show them. On the topic of scope, I agree with what I believe Phillip Wood implied, that excessive refactoring should not be required to adopt this pattern. As such I will keep this in mind in the next iteration.

There is more to discuss about strings vs error codes and the future of error codes as well as memory allocation, but this is probably enough for now. I may be interested to try out the error_context as well as a concept next just to see what it would be like, but do people agree with the differential analysis so far and changes proposed? And curious if you have any other thoughts?

- Philip

Quoted 56 lines · Jeff King
Quoted 7 lines · Patrick Steinhardt

While we're already at it throwing ideas around, I also have to wonder whether this would be a long-term solution towards computer-friendly errors. One of the problems we quite frequently hit in Gitaly is that we are forced to parse error messages in order to figure out why exactly something has failed. Needless to say, this is quite fragile and also feels very wrong.

Quoted 8 lines

Now if we had a more structured way to pass errors around this might also enable us to convey more meaning to the caller of Git commands. In a hypothetical world where all errors were using an explicit error type, then this error type could eventually become richer and contain more information that is relevant to the calling script. And if such rich error information was available, then it would not be that far fetched to ask Git to emit errors in a computer-parsable format like for example JSON.

I think what I'm proposing (and if I understand correctly what Phillip was thinking) is somewhat orthogonal. I agree that structured errors are nice for computers to read. But it does open up a pretty big can of worms regarding classifying each error, especially as root causes are often multi-level.

For example, imagine that the caller asks to resolve a ref. We might get a syscall error opening the loose ref. Or we might get one opening the packed-refs file (in a reftable world, you might imagine errors opening various other files). What is the structured error? Obviously it is "we can't resolve that ref" at some level. But the caller might want to know about the failed open (whether it is just ENOENT, or if we ran into EPERM or even EIO).

Or looking at higher levels; if I ask for the merge base between A and B, but one of those can't be resolved, how do we communicate that error? It is some sort of "cannot resolve" error, but it needs to be parameterized to know which is which.

All of those questions can be answered, of course, but now we are developing a micro-format that lets us describe all errors in a standardized way. And I think that is going to put a burden on the code which is generating the errors (and potentially on the consumers, too, if they have to decipher the structure to figure out what they want).

Whereas what I was really advocating for is punting on the structured thing entirely. We keep our unstructured string errors for the most part, but we simply let the caller pass in a context that tells us what to do with them. That lets us keep providing specific error messages from low-level functions without printing to stderr or exiting, which higher-level code (especially lib-ified code) would not want.

I think it could also be the first building block for making more structured errors (since those low-level callers are free to provide lots of details), but it doesn't have to be.

-Peff