Skip to content

Commit a9bd1fb

Browse files
committed
Never replay an envelope after a jq-backed write has begun
The fallback writer was not the path that retried — app.Err was. When a filter emits results and then fails, writeJQ has already written, and falling through to the plain writer appended a second, unfiltered envelope. 'todos create --jq ".error, error(\"stop\")"' printed both a bare line and a full JSON document to stdout, which is two incompatible outputs for the machine consumer the filter exists to serve. Once a jq-backed write has begun, stdout is final: report the render failure on stderr and exit with the original code. Without a filter nothing partial can have been written through one, so the plain fallback stays as the last resort for a broken pipe. jqUsable stays — it covers the other path, where no app existed yet — but it was never able to prevent this, and the comment that implied otherwise now describes only the path it governs. The old unit test drove two writers directly rather than Execute, so it could not have caught this. Replaced with a predicate test, plus an e2e case that runs the real binary and asserts stdout holds exactly one document; removing the fix makes it fail.
1 parent e4d545d commit a9bd1fb

4 files changed

Lines changed: 81 additions & 32 deletions

File tree

‎e2e/stdin_dash.bats‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,35 @@ load test_helper
110110
assert_success
111111
assert_output_contains "--description"
112112
}
113+
114+
115+
# --jq error rendering. Not stdin-specific, but it shares this file's contract:
116+
# exactly one document reaches stdout, so a machine consumer can parse it.
117+
118+
@test "a jq filter that fails partway leaves one document on stdout" {
119+
create_credentials
120+
create_global_config '{"account_id": 99999}'
121+
122+
# This filter emits .error, then raises. writeJQ streams results as it
123+
# produces them, so the first line is already on stdout when it fails —
124+
# replaying the envelope would append a second, incompatible document.
125+
run bash -c "basecamp todos create --jq '.error, error(\"stop\")' 2>/dev/null < /dev/null"
126+
assert_failure
127+
[ "${#lines[@]}" -eq 1 ]
128+
assert_output_contains "required"
129+
130+
# The failure is still reported, on stderr.
131+
run bash -c "basecamp todos create --jq '.error, error(\"stop\")' 2>&1 >/dev/null < /dev/null"
132+
assert_output_contains "--jq"
133+
}
134+
135+
@test "an unparseable jq filter still renders an error raised before validation" {
136+
create_credentials
137+
create_global_config '{"account_id": 99999}'
138+
139+
# The stray-dash guard fires before --jq is validated, so the envelope would
140+
# otherwise be rendered through an unparseable filter and print nothing.
141+
run bash -c "printf 'x' | basecamp --jq '.[invalid' - 2>/dev/null"
142+
assert_failure
143+
assert_output_contains "does not read stdin"
144+
}

‎internal/cli/cobra_error_test.go‎

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package cli
22

33
import (
4-
"bytes"
54
"errors"
65
"testing"
76

@@ -87,24 +86,25 @@ func TestTransformCobraErrorIgnoresUnanchoredArityText(t *testing.T) {
8786
assert.Equal(t, msg, err.Error())
8887
}
8988

90-
// An invalid --jq paired with an error raised before jq validation used to
91-
// exit non-zero having printed nothing: the fallback writer tried to render the
92-
// envelope through the broken filter, and its failure was discarded. The error
93-
// the caller needs outranks the filter they asked for.
94-
func TestInvalidJQFilterStillRendersAnEarlierError(t *testing.T) {
95-
var buf bytes.Buffer
96-
writer := output.New(output.Options{
97-
Format: output.FormatJSON,
98-
Writer: &buf,
99-
JQFilter: ".[invalid",
100-
})
101-
102-
require.Error(t, writer.Err(output.ErrUsage("stray dash")),
103-
"a broken filter must report that it could not render")
104-
require.Empty(t, buf.String(), "and must not have written a usable envelope")
105-
106-
buf.Reset()
107-
plain := output.New(output.Options{Format: output.FormatJSON, Writer: &buf})
108-
require.NoError(t, plain.Err(output.ErrUsage("stray dash")))
109-
assert.Contains(t, buf.String(), "stray dash")
89+
// jqUsable decides whether the fallback writer may keep a filter. It answers
90+
// only the question that is knowable before any output exists — a filter that
91+
// parses and compiles can still fail partway through producing results, which
92+
// is why the jq-backed path never retries a failed write. That end-to-end
93+
// property needs the real binary and is covered in e2e/stdin_dash.bats; this
94+
// only pins the predicate.
95+
func TestJQUsable(t *testing.T) {
96+
for _, tc := range []struct {
97+
name string
98+
filter string
99+
want bool
100+
}{
101+
{"valid", ".error", true},
102+
{"parse failure", ".[invalid", false},
103+
{"compile failure", ".foo | undefined_function", false},
104+
{"valid but fails at runtime", `.error, error("stop")`, true},
105+
} {
106+
t.Run(tc.name, func(t *testing.T) {
107+
assert.Equal(t, tc.want, jqUsable(tc.filter))
108+
})
109+
}
110110
}

‎internal/cli/root.go‎

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -396,12 +396,27 @@ func Execute() {
396396
disableJQ := output.IsJQError(err)
397397
if !disableJQ {
398398
if app := appctx.FromContext(executedCmd.Context()); app != nil {
399-
if writeErr := app.Err(err); writeErr == nil {
399+
writeErr := app.Err(err)
400+
if writeErr == nil {
400401
os.Exit(output.ExitCodeFor(apiErr.Code))
401402
}
402-
// app.Err() write failed (e.g. jq runtime error on the error
403-
// envelope, or broken pipe). Disable jq in the fallback writer
404-
// to avoid replaying the same failure.
403+
404+
// The write failed. When a filter was in play it may already
405+
// have emitted results — writeJQ streams each one as it is
406+
// produced, so a filter like `.error, error("stop")` prints
407+
// before it fails. Replaying the envelope on stdout would
408+
// append a second, unfiltered document to the first, which is
409+
// two incompatible outputs for the machine consumer the filter
410+
// exists to serve. Once a jq-backed write has begun, stdout is
411+
// final: report the failure on stderr and stop.
412+
if jq, _ := cmd.PersistentFlags().GetString("jq"); jq != "" {
413+
fmt.Fprintf(os.Stderr, "error rendering error output through --jq: %v\n", writeErr)
414+
os.Exit(output.ExitCodeFor(apiErr.Code))
415+
}
416+
417+
// No filter: nothing partial can have been written through one,
418+
// so the plain fallback below is still the right last resort
419+
// (e.g. a broken pipe).
405420
disableJQ = true
406421
}
407422
}
@@ -439,13 +454,14 @@ func Execute() {
439454
format = output.FormatJSON
440455
}
441456

442-
// An unusable filter must not swallow the error: --jq is validated in
443-
// the pre-run, so an error raised *before* that check would otherwise
444-
// be rendered through an unparseable filter and exit non-zero having
445-
// printed nothing. Decide here instead of retrying after a failed
446-
// write — writeJQ streams each result as it produces it, so a filter
447-
// that fails partway (".error, error(\"stop\")") has already written,
448-
// and a second pass would emit two incompatible envelopes.
457+
// This path runs only when nothing has been written yet: either no app
458+
// was available (an error raised before it was built) or no filter was
459+
// in play. An unusable filter must not swallow the error — --jq is
460+
// validated in the pre-run, so an error raised *before* that check
461+
// would otherwise render through an unparseable filter and exit
462+
// non-zero having printed nothing. Decide usability up front rather
463+
// than retrying after a failed write, which is what the jq-backed path
464+
// above refuses to do.
449465
if jqFilter != "" && !jqUsable(jqFilter) {
450466
jqFilter = ""
451467
}

‎verify‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Subproject commit ac3f38ea2576d3c872c1169adcd089cf0f19c79d

0 commit comments

Comments
 (0)