Subject: TAP output format in pg_regress

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 22 Feb 2022 00:08:11 +0100

Starting a new thread on the TAP patch from the "[RFC] building postgres with
meson" thread at [email-masked] to have
somewhere to discuss this patch.

> On 21 Feb 2022, at 17:52, Andres Freund <[email-masked]> wrote:
> On 2021-10-13 13:54:10 +0200, Daniel Gustafsson wrote:

>> I added a --tap option for TAP output to pg_regress together with Jinbao Chen
>> for giggles and killing some time a while back.
> 
> Sorry for not replying to this earlier. I somehow thought I had, but the
> archives disagree.

No worries, I had forgotten about it myself.

> I think this would be great.

Cool, I'll pick it up again then.  I didn't have time to dig into the patch
tonight but the attached is a rebased version which just cleans up the bitrot
it had accumulated to the point where it at least compiles and seems to run.

>> One thing that came out of this, is that we don't really handle the ignored
>> tests in the way the code thinks it does for normal output, the attached treats
>> ignored tests as SKIP tests.
> 
> I can't really parse the first sentence...

I admittedly don't remember exactly what I meant, but I'm fairly sure it's
wrong.  I think I thought ignored tests were counted incorrectly, but skimming
the patch just now I think it's doing it wrong as it counts ignored as failed
even if they passed.  I'll fix that.

>> 	if (exit_status != 0)
>> 		log_child_failure(exit_status);
>> @@ -2152,6 +2413,7 @@ regression_main(int argc, char *argv[],
>> 		{"config-auth", required_argument, NULL, 24},
>> 		{"max-concurrent-tests", required_argument, NULL, 25},
>> 		{"make-testtablespace-dir", no_argument, NULL, 26},
>> +		{"tap", no_argument, NULL, 27},
>> 		{NULL, 0, NULL, 0}
>> 	};
> 
> I'd make it a --format=(regress|tap) or such.

That makes sense, done in the attached.

--
Daniel Gustafsson		https://vmware.com/

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 22 Feb 2022 15:10:11 +0100

> On 22 Feb 2022, at 00:08, Daniel Gustafsson <[email-masked]> wrote:

> I'll fix that.

The attached v3 fixes that thinko, and cleans up a lot of the output which
isn't diagnostic per the TAP spec to make it less noisy.  It also fixes tag
support used in the ECPG tests and a few small cleanups.  There is a blank line
printed which needs to be fixed, but I'm running out of time and wanted to get
a non-broken version on the list before putting it aside for today.

The errorpaths that exit(2) the testrun should be converted to "bail out" lines
when running with TAP output, but apart from that I think it's fairly spec
compliant.

---

From: Andres Freund <[email-masked]>
Date: Tue, 22 Feb 2022 09:13:31 -0800

Hi,

Thanks for the updated version!

> when running with TAP output, but apart from that I think it's fairly spec

I'd much rather not use BAIL - I haven't gotten around to doing anything about
it, but I really want to get rid of nearly all our uses of bail:

https://www.postgresql.org/message-id/20220213232249.7sevhlioapydla37%40alap3.anarazel.de

Greetings,

Andres Freund

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 22 Feb 2022 22:04:38 +0100

> On 22 Feb 2022, at 18:13, Andres Freund <[email-masked]> wrote:

> it, but I really want to get rid of nearly all our uses of bail:

Point.  We already error out on stderr in pg_regress so we could probably make
die() equivalent output to keep the TAP parsing consistent.  At any rate,
awaiting the conclusions on the bail thread and simply (for some value of)
replicating that in this patch is probably the best option?

---

From: Andres Freund <[email-masked]>
Date: Mon, 21 Mar 2022 16:49:24 -0700

Hi,

> when running with TAP output, but apart from that I think it's fairly spec

This is failing with segmentation faults on cfbot:
https://cirrus-ci.com/task/4879227009892352?logs=test_world#L21

Looks like something around isolationtester is broken?

Unfortunately there's no useful backtraces for isolationtester. Not sure
what's up there.

Seems like we might not have energy to push this forward in the next two
weeks, so maybe the CF entry should be marked returned or moved for now?

Greetings,

Andres Freund

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 24 Mar 2022 13:44:51 +0100

> On 22 Mar 2022, at 00:49, Andres Freund <[email-masked]> wrote:

> Looks like something around isolationtester is broken?

It could be triggered by plpgsql tests as well, and was (as usual) a silly
mistake easily fixed when found.  The attached survices repeated check-world
for me.

> weeks, so maybe the CF entry should be marked returned or moved for now?

Since there is little use for this without the Meson branch, it should target
the same version as that patch. I'll move the patch to the next CF for now.

As we discussed off-list I extended this patchset with an attempt to minimize
noise as per [email-masked], but it's not
yet done.  The attached has a rough draft of adding a --verbose option which
gives the current output (and potentially more for debugging), but which by
default is off producing minimal noise.

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 29 Jun 2022 21:50:45 +0200

Attached is a new version of this patch, which completes the TAP output format
option such that all codepaths emitting output are TAP compliant.  The verbose
option is fixed to to not output extraneous newlines which the previous PoC
did.  The output it made to conform to the original TAP spec since v13/14 TAP
parsers seem less common than those that can handle the original spec.  Support
for the new format additions should be quite simple to add should we want that.

Running pg_regress --verbose should give the current format output.

I did end up combining TAP and --verbose into a single patch, as the TAP format
sort of depends on the verbose flag as TAP has no verbose mode.  I can split it
into two separate should a reviewer prefer that.

---

From: Peter Eisentraut <[email-masked]>
Date: Mon, 4 Jul 2022 16:27:20 +0200

> into two separate should a reviewer prefer that.

I'm not sure what to make of all these options.  I think providing a TAP 
output for pg_regress is a good idea.  But then do we still need the old 
output?  Is it worth maintaining two output formats that display exactly 
the same thing in slightly different ways?

What is the purpose of the --verbose option?  When and how is one 
supposed to activate that?  The proposed default format now hides the 
fact that some tests are started in parallel.  I remember the last time 
I wanted to tweak the output of the parallel tests, people were very 
attached to the particular timing and spacing of the current output.  So 
I'm not sure people will like this.

The timing output is very popular.  Where is that in the TAP output?

More generally, what do you envision we do with this feature?  Who is it 
for, what are the tradeoffs, etc.?

---

From: Tom Lane <[email-masked]>
Date: Mon, 04 Jul 2022 10:39:37 -0400

Probably is, because this is bad:

> ... The proposed default format now hides the 

> The timing output is very popular.  Where is that in the TAP output?

Both of those things are fairly critical for test development.  You
need to know what else might be running in parallel with a test case,
and you need to know whether you just bloated the runtime unreasonably.

More generally, I'm unhappy about the proposal that TAP should become
the default output.  There is nothing particularly human-friendly
about it, whereas the existing format is something we have tuned to
our liking over literally decades.  I don't mind if there's a way to
get TAP when you're actually intending to feed it into a TAP-parsing
tool, but I am not a TAP-parsing tool and I don't see why I should
have to put up with it.

			regards, tom lane

---

From: Peter Eisentraut <[email-masked]>
Date: Mon, 4 Jul 2022 21:33:36 +0200

> and you need to know whether you just bloated the runtime unreasonably.

I don't think there is a reason these couldn't be shown in TAP output as 
well.

Even if we keep the two output formats in parallel, it would be good if 
they showed the same set of information.

---

From: Andres Freund <[email-masked]>
Date: Mon, 4 Jul 2022 13:06:17 -0700

Hi,

> and you need to know whether you just bloated the runtime unreasonably.

That should be doable with tap as well - afaics the output of that could
nearly be the same as now, preceded by a #.

The test timing output could (and I think should) also be output - but if I
read the tap specification correctly, we'd either need to make it part of the
test "description" or on a separate line.

> tool, but I am not a TAP-parsing tool and I don't see why I should

I'm mostly interested in the tap format because meson's testrunner can parse
it - unsurprisingly it doesn't understand the current regress output. It's a
lot nicer to immediately be pointed to the failed test(s) than having to scan
through the output "manually".

Greetings,

Andres Freund

---

From: Andres Freund <[email-masked]>
Date: Mon, 4 Jul 2022 13:13:52 -0700

Hi,

On 2022-06-29 21:50:45 +0200, Daniel Gustafsson wrote:
> @@ -279,8 +648,7 @@ stop_postmaster(void)
>  		r = system(buf);
>  		if (r != 0)
>  		{
> -			fprintf(stderr, _("\n%s: could not stop postmaster: exit code was %d\n"),
> -					progname, r);
> +			pg_log_error("could not stop postmaster: exit code was %d", r);
>  			_exit(2);			/* not exit(), that could be recursive */
>  		}

There's a lot of stuff like this. Perhaps worth doing separately? I'm not sure
I unerstand where you used bail and where not. I assume it's mostly arund use
uf _exit() vs exit()?

> +				test_status_ok(tests[i]);
>  
>  			if (statuses[i] != 0)
>  				log_child_failure(statuses[i]);
>  
>  			INSTR_TIME_SUBTRACT(stoptimes[i], starttimes[i]);
> -			status(_(" %8.0f ms"), INSTR_TIME_GET_MILLISEC(stoptimes[i]));
> +			runtime(tests[i], INSTR_TIME_GET_MILLISEC(stoptimes[i]));

Based on the discussion downthread, let's just always compute this and display
it even in the tap format?

Greetings,

Andres Freund

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 4 Jul 2022 23:48:02 +0200

> On 4 Jul 2022, at 22:13, Andres Freund <[email-masked]> wrote:
> 
> Hi,
> 

Since bail will cause the entire testrun to be considered a failure, the idea
was to avoid using bail() for any errors in tearing down the test harness after
an otherwise successful test run.

Moving to pg_log_error() can for sure be broken out into a separate patch from
the rest of the set (if we at all want to do that, but it seemed logical to
address when dealing with other output routines).

> it even in the tap format?

Sure, it's easy enough to do and include in the test description.  The reason I
left it out is that the test runners I played around with all hide those
details and only show a running total.  That of course doesn't mean that all
runners will do that (and anyone running TAP output for human consumption will
want it), so I agree with putting it in, I'll fix that up in a v6 shortly.

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 5 Jul 2022 00:06:04 +0200

> On 4 Jul 2022, at 16:27, Peter Eisentraut <[email-masked]> wrote:
> 
> I'm not sure what to make of all these options.  I think providing a TAP output for pg_regress is a good idea.  But then do we still need the old output?  Is it worth maintaining two output formats that display exactly the same thing in slightly different ways?

If we believe that TAP is good enough for human consumption and not just as
input to test runners then we don't.  Personally I think the traditional format
is more pleasant to read than raw TAP output when running tests.

> What is the purpose of the --verbose option?  When and how is one supposed to activate that?  The proposed default format now hides the fact that some tests are started in parallel.

The discussion on this was in [email-masked]
where it was proposed that we could cut the boilerplate.  Thinking on it I
agree that the parallel run info should be included even without --verbose so
I'll add that back.  In general, running with --verbose should ideally only be
required for troubleshooting setup/teardown issues with testing.

>  I remember the last time I wanted to tweak the output of the parallel tests, people were very attached to the particular timing and spacing of the current output.  So I'm not sure people will like this.
> 

As I mentioned in the mail upthread, TAP runners generally hide that info and
only show a running total.  That being said, I do agree with adding back so
I'll do that in a new version of the patch.

> More generally, what do you envision we do with this feature?  Who is it for, what are the tradeoffs, etc.?

In general, my thinking with this was that normal testruns started with make
check (or similar) by developers would use the traditional format (albeit less
verbose) and that the TAP output was for automated test runners in general and
the meson test runner in particular.  The TAP format is an opt-in with the
traditional format being the default.

The tradeoff is of course that maintaining two output formats is more work than
maintaining one, but it's not really something we change all that often so that
might not be too heavy a burden.

I personally didn't see us replacing the traditional format for "human
readable" runs, if that's where the discussion is heading then the patch can
look quite different.  Having test output format parity with supported back
branches seemed like a good idea to me at the time of writing at least.

---

From: Tom Lane <[email-masked]>
Date: Mon, 04 Jul 2022 18:06:31 -0400

> nearly be the same as now, preceded by a #.

I don't mind minor changes like prefixing # --- I just don't want
to lose information.

			regards, tom lane

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 5 Jul 2022 00:11:13 +0200

> On 4 Jul 2022, at 16:39, Tom Lane <[email-masked]> wrote:
> 
> the default output.  

That's not my proposal though, my proposal is that the traditional format
should be the default output (with the parallel test info added back, that was
my bad), and that TAP is used in automated test runners like in meson.  Hiding
the timing in TAP was (as mentioned upthread) since TAP test runners generally
never show that anyways, but I'll add it back since it clearly doesn't hurt to
have even there.

> There is nothing particularly human-friendly

I totally agree, and that's why the patch has the traditional format - without
all the boilerplate - as the default.  Unless opting-in there is no change over
today, apart from the boilerplate.

---

From: Andres Freund <[email-masked]>
Date: Mon, 4 Jul 2022 15:58:31 -0700

Hi,

> is more pleasant to read than raw TAP output when running tests.

I think with a bit of care the tap output could be nearly the same
"quality". It might not be the absolute "purest" tap output, but who cares.

test tablespace                   ... ok          418 ms
parallel group (20 tests):  oid char int2 varchar name int4 text pg_lsn regproc txid money boolean uuid float4 int8 float8 bit enum rangetypes numeric
     boolean                      ... ok           34 ms
     char                         ... ok           20 ms
     name                         ... ok           26 ms

isn't that different from

ok 1 - tablespace           418ms
# parallel group (20 tests):  oid char int2 varchar name int4 text pg_lsn regproc txid money boolean uuid float4 int8 float8 bit enum rangetypes numeric
ok 2 -      boolean        34ms
ok 3 -      char           20ms
ok 4 -      name           26ms

or whatever.

For non-parallel tests I think we currently print the test name before running
the test, which obviously doesn't work well when needing to print the 'ok'
'not ok' first. We could just print
# non-parallel group tablespace
or such? That doesn't

I wonder if for parallel tests we should print the test number based on the
start of the test rather than the finish time? Hm, it also looks like it's
legal to just leave the test number out?

> where it was proposed that we could cut the boilerplate.

I think that was more about things like CREATE DATABASE etc. And I'm not sure
we need an option to keep showing those details.

> I'll do that in a new version of the patch.

FWIW, meson's testrunner shows the individual tap output when using -v.

One test where using -v is a problem is pg_dump's tests - the absurd number of
8169 tests makes showing that decidedly not fun.

> Having test output format parity with supported back branches seemed like a
> good idea to me at the time of writing at least.

That's of course nice, but it also kind of corners us into not evolving the
default format, which I don't think is warranted...

Greetings,

Andres Freund

---

From: Tom Lane <[email-masked]>
Date: Mon, 04 Jul 2022 21:56:24 -0400

> "quality". It might not be the absolute "purest" tap output, but who cares.

+1

> 'not ok' first.

Is this still a consideration?  We got rid of serial_schedule some
time ago.

> start of the test rather than the finish time?

I think we need the test number to be stable, so it had better be the
ordering appearing in the schedule file.  But we already print the
results in that order.

			regards, tom lane

---

From: Andres Freund <[email-masked]>
Date: Mon, 4 Jul 2022 19:40:11 -0700

Hi,

> Is this still a consideration?  We got rid of serial_schedule some

Not really for the main tests, there's a few serial steps, but not enough that
a bit additional output would be an issue. I think all tests in contrib are
serial though, and some have enough tests that it might be annoying?

> ordering appearing in the schedule file.  But we already print the

I remembered some asynchronizity, but apparently that's just the "parallel
group" line.

Greetings,

Andres Freund

---

From: Jacob Champion <[email-masked]>
Date: Tue, 2 Aug 2022 11:44:30 -0700

This entry has been waiting on author input for a while (our current
threshold is roughly two weeks), so I've marked it Returned with
Feedback.

Once you think the patchset is ready for review again, you (or any
interested party) can resurrect the patch entry by visiting

    https://commitfest.postgresql.org/38/3559/

and changing the status to "Needs Review", and then changing the
status again to "Move to next CF". (Don't forget the second step;
hopefully we will have streamlined this in the near future!)

Thanks,
--Jacob

---

From: Daniel Gustafsson <[email-masked]>
Date: Wed, 17 Aug 2022 23:04:20 +0200

Attached is a new version of the pg_regress TAP patch which - per reviewer
feedback - does away with dual output formats and just converts the existing
output to be TAP complaint.  The idea was to keep it fairly human readable
while still be TAP compliant enough that running it with prove (with a tiny
Perl wrapper) works.  This version also strips away the verbose output which
these days isn't terribly useful and mainly consume vertical space.  Another
feature of the patch is to switch error logging to using the common frontend
logging rather than pg_regress rolling its own.  The output from pg_log_error
is emitted verbatim by prove as it's on stderr.

I based the support on the original TAP specification and not the new v13 or
v14 since it seemed unclear how well those are supported in testrunners.  If
v14 is adopted by testrunners there are some better functionality for reporting
errors that we could use, but for how this version seems a safer option.

A normal "make check" with this patch applied now looks like this:

+++ regress check in src/test/regress +++
# running on port 61696 with PID 57910
ok 1 - test_setup                       326 ms
ok 2 - tablespace                       401 ms
# parallel group (20 tests):  varchar char oid pg_lsn txid int4 regproc money int2 uuid float4 text name boolean int8 enum float8 bit numeric rangetypes
ok 3 - boolean                          129 ms
ok 4 - char                              73 ms
ok 5 - name                             117 ms
ok 6 - varchar                           68 ms
<...snip...>
ok 210 - memoize                        137 ms
ok 211 - stats                          851 ms
# parallel group (2 tests):  event_trigger oidjoins
ok 212 - event_trigger                  138 ms
not ok 213 - oidjoins                   190 ms
ok 214 - fast_default                   149 ms
1..214
# 1 of 214 tests failed.
# The differences that caused some tests to fail can be viewed in the
# file "/<path>/src/test/regress/regression.diffs".  A copy of the test summary that you see
# above is saved in the file "/<path>/src/test/regress/regression.out".

The ending comment isn't currently shown when executed via prove as it has to
go to STDERR for that to work, and I'm not sure that's something we want to do
in the general case.  I don't expect running the pg_regress tests via prove is
going to be the common case.  How does the meson TAP ingestion handle
stdout/stderr?

And for the sake of completeness, even though we all know this by heart, a
similar run from the current output format looks like:

+++ regress check in src/test/regress +++
============== creating temporary instance            ==============
============== initializing database system           ==============
============== starting postmaster                    ==============
running on port 61696 with PID 61955
============== creating database "regression"         ==============
CREATE DATABASE
ALTER DATABASE
ALTER DATABASE
ALTER DATABASE
ALTER DATABASE
ALTER DATABASE
ALTER DATABASE
============== running regression test queries        ==============
test test_setup                   ... ok          469 ms
test tablespace                   ... ok          415 ms
parallel group (20 tests):  varchar char oid name int2 pg_lsn int4 txid text uuid regproc boolean money float4 int8 float8 bit enum numeric rangetypes
     boolean                      ... ok          105 ms
     char                         ... ok           64 ms
     name                         ... ok           70 ms
     varchar                      ... ok           55 ms
<...snip...>
     memoize                      ... ok          149 ms
     stats                        ... ok          873 ms
parallel group (2 tests):  event_trigger oidjoins
     event_trigger                ... FAILED      142 ms
     oidjoins                     ... FAILED      208 ms
test fast_default                 ... ok          172 ms
============== shutting down postmaster               ==============

========================
 2 of 214 tests failed.
========================

The differences that caused some tests to fail can be viewed in the
file "/<path>/src/test/regress/regression.diffs".  A copy of the test summary that you see
above is saved in the file "/<path>/src/test/regress/regression.out".

There is a slight reduction in information, for example around tests run
serially vs in a parallel group.  This could perhaps be handled by marking the
test name in some way like "tablespace (serial) or prefixing with a symbol or
somerthing.  I can take a stab at that in case we think that level of detail is
important to preserve.

---

From: Andres Freund <[email-masked]>
Date: Wed, 17 Aug 2022 15:49:49 -0700

Hi,

On 2022-08-17 23:04:20 +0200, Daniel Gustafsson wrote:
> output to be TAP complaint.

Cool.

> Perl wrapper) works.

Wonder if we could utilize that for making failures of 002_pg_upgrade.pl and
027_stream_regress.pl easier to understand, by reporting pg_regress' steps as
part of the outer test. But that'd probably be at least somewhat hard, due to
the embedded test count etc.

> This version also strips away the verbose output which these days isn't
> terribly useful and mainly consume vertical space.

Yay.

> Another feature of the patch is to switch error logging to using the common
> frontend logging rather than pg_regress rolling its own.  The output from
> pg_log_error is emitted verbatim by prove as it's on stderr.

Sounds good.

> errors that we could use, but for how this version seems a safer option.

Yep, that makes sense.

> # above is saved in the file "/<path>/src/test/regress/regression.out".

I'm happy with that compared to our current output.

> going to be the common case.  How does the meson TAP ingestion handle

It'll parse stdout for tap output and log stderr output separately.

> somerthing.  I can take a stab at that in case we think that level of detail is

I think we could just indent the test "description" for tests in parallel
groups:

I.e. instead of

ok 1 - test_setup                       326 ms
ok 2 - tablespace                       401 ms

do

ok 1 - test_setup                       326 ms
ok 2 - tablespace                       401 ms

that'd make it sufficiently clear, and is a bit more similar to the current
format?

I wonder if we should indent the test name so that the number doesn't cause
wrapping? And perhaps we can skip the - in that case?

I.e. instead of:

ok 9 - name                             117 ms
ok 10 - varchar                          68 ms
..
ok 99 - something                        60 ms
ok 100 - memoize                        137 ms

something like:

ok 9    name                            117 ms
ok 10   varchar                          68 ms
...
ok 99   something                        60 ms
ok 100  memoize                         137 ms

with parallel tests:

ok 9    name                            117 ms
# parallel group (2 tests):  varchar varchar2
ok 10           varchar                  68 ms
ok 11           varchar2                139 ms
ok 12   varchar3                         44 ms
ok 99   something                        60 ms
ok 100  memoize                         137 ms

Greetings,

Andres Freund

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 18 Aug 2022 13:24:20 +0200

> On 18 Aug 2022, at 00:49, Andres Freund <[email-masked]> wrote:

> the embedded test count etc.

I have a feeling it might require some quite bespoke logic to tie it together
(which may not be worth it in the end) but I'll have a look.

> I'm happy with that compared to our current output.

Great!  Once this thread has settled on a format, maybe it should go to a
separate -hackers thread to get more visibility and (hopefully) buy-in for such
a change.

One thing I haven't researched yet is if the Buildfarm or CFBot parses the
current output in any way or just check the exit status of the testrun.

> It'll parse stdout for tap output and log stderr output separately.

Then I think this patch will be compatible with that.

> that'd make it sufficiently clear, and is a bit more similar to the current

Thats a better option, done that way.

> wrapping?

The tricky part there is that we don't know beforehands how many tests will be
run.  We could add a first pass over the schedule, which seems excessive for
this, or align with a fixed max such that 9999 number of tests is the maximum
number of tests which will print neatly aligned.

> And perhaps we can skip the - in that case?

The dash is listed as "Recommended" but not required in the TAP spec (including
up to v14) so we can skip it.

With these changes, the "worst case" output in terms of testnames alignment
would be something like this (assuming at most 9999 tests):

ok 211               stats                          852 ms
# parallel group (2 tests):  event_trigger oidjoins
ok 212               event_trigger                  149 ms
not ok 213           oidjoins                       194 ms
ok 214       fast_default                           178 ms
1..214

I think that's fairly readable, and not that much different from today.

---

From: Andrew Dunstan <[email-masked]>
Date: Thu, 18 Aug 2022 10:40:22 -0400

> current output in any way or just check the exit status of the testrun.

Buildfarm: just the status.

cheers

andrew

--
Andrew Dunstan
EDB: https://www.enterprisedb.com

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 1 Sep 2022 14:21:18 +0200

> On 18 Aug 2022, at 16:40, Andrew Dunstan <[email-masked]> wrote:
> 

Thanks for confirming, the same is true for CFBot AFAICT.

Attached is a v8 which fixes a compiler warning detected by the CFBot.

---

From: Andres Freund <[email-masked]>
Date: Sat, 1 Oct 2022 18:01:53 -0700

Hi,

> Attached is a v8 which fixes a compiler warning detected by the CFBot.

cfbot at the moment does show a warning. A bit surprised to see this warning
enabled by default in gcc, but it seems correct here:

[20:57:02.892] make -s -j${BUILD_JOBS} clean
[20:57:03.326] time make -s -j${BUILD_JOBS} world-bin
[20:57:12.882] pg_regress.c: In function ‘bail’:
[20:57:12.882] pg_regress.c:219:2: error: function ‘bail’ might be a candidate for ‘gnu_printf’ format attribute [-Werror=suggest-attribute=format]
[20:57:12.882]   219 |  vsnprintf(tmp, sizeof(tmp), fmt, ap);
[20:57:12.882]       |  ^~~~~~~~~

Now that meson is merged, it'd be worthwhile to change the invocation for
pg_regress in the toplevel meson.build (search for "Test Generation").

Greetings,

Andres Freund

---

From: Nikolay Shaplov <[email-masked]>
Date: Thu, 10 Nov 2022 13:44:54 +0300

Hi! Do this patch still need reviewer, or reviewer field in commit-fest have 
been left empty by mistake?

I am fan of TAP-tests, so I am quite happy that pg_regress output changed to 
TAP tests...

I've checked new output, if is conform TAP specification. Checked that prove 
consumes new pg_regress output well.

Did not found quick way to include prove TAP harness right into Makefile, so I 
check dumped output, but it is not really important for now, I guess.

As for the code, I gave it a quick readthrough... And main issue I've stumbled 
was here:

--------------
 indent = 36 - (parallel ? 8 : 0) - floor(log10(testnumber) + 1);

	status("ok %-5i     %s%-*s %8.0f ms",
	   testnumber, (parallel ? "        " : ""), indent,
	   testname,
	   runtime);
--------------

This peace of code has non-obvious logic (I can solve it without taking time 
for deep thinking) and this code (almost similar) is repeated three times. 
This is hard to support, and error prone solution. 

I would suggest to add one _print_test_status function, that also accepts 
status string and do this complex calculations and formatting only once (
"# SKIP (ignored)" should also added as %s, so we have only one print with 
complex format string).

Then you will have to read check and fix it only once.  

And may be it would be good to make this calculations more human-readable...

If this patch really needs reviewer and my way of thinking is acceptable, 
please let me know, I will set myself as a reviewer and will dig further into 
the code.

-- 
Nikolay Shaplov aka Nataraj
Fuzzing Engineer at Postgres Professional
Matrix IM: @dhyan:nataraj.su

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 17 Nov 2022 11:36:13 +0100

> On 10 Nov 2022, at 11:44, Nikolay Shaplov <[email-masked]> wrote:

> consumes new pg_regress output well.

Great!

> check dumped output, but it is not really important for now, I guess.

I think we'll start by adding TAP to the meson testrunner and await to see
where the make buildsystem ends up before doing anything there.

> As for the code, I gave it a quick readthrough... And main issue I've stumbled 

Re-reading this I realized this was actually no longer needed as the testnumber
is padded, so it's all removed.  I've also refactored printing into a separate
function.

> please let me know, I will set myself as a reviewer and will dig further into 

Please do, reviewers are always welcome (on all patches), it's an extremely
valuable contribution to the community.

The attached contains these fixes, a small cleanups and the GCC warning on
printf attribute that Andres pointed to upthread.

The "make check" output now looks like the below, in an attempt to keep it
recognizable while still TAP compliant.  fast_default is not running as part of
a parallel group, hence the different indentation.

ok 207              compression                        191 ms
not ok 208          memoize                            144 ms
ok 209              stats                             1423 ms
# parallel group (2 tests):  event_trigger oidjoins
ok 210              event_trigger                      117 ms
ok 211              oidjoins                           166 ms
ok 212       fast_default                              143 ms
1..212
# 1 of 212 tests failed.
# The differences that caused some tests to fail can be viewed in the
# file "/Users/danielg/dev/postgresql/hacking/src/test/regress/regression.diffs".  A copy of the test summary that you see
# above is saved in the file "/Users/danielg/dev/postgresql/hacking/src/test/regress/regression.out".

Patch 0002 makes meson treat the output as TAP, which makes "meson test" look
like this:

20/75 postgresql:isn / isn/regress OK 4.10s 1 subtests passed
21/75 postgresql:regress / regress/regress OK 22.73s 212 subtests passed
22/75 postgresql:intarray / intarray/regress OK 5.01s 1 subtests passed
...
73/75 postgresql:test_ddl_deparse / test_ddl_deparse/regress OK 13.18s 21 subtests passed
74/75 postgresql:test_shm_mq / test_shm_mq/regress OK 9.14s 1 subtests passed
75/75 postgresql:ecpg / ecpg/ecpg OK 23.68s 62 subtests passed

I'm not sure if that's the right way to go about configuring regress tests as
TAP emitting, but it at least shows that meson is properly parsing the output
AFAICT.

---

From: Andres Freund <[email-masked]>
Date: Thu, 17 Nov 2022 10:37:49 -0800

Hi,

+1

prove IME is of, uh, very questionable quality IME. I do not want to run
pg_regress/isolation tests through that unnecessarily. It'd not gain us much
anyway, afaict. And we don't want it as a hard dependency either.

> TAP emitting, but it at least shows that meson is properly parsing the output

Looks correct to me.

> @@ -742,13 +823,13 @@ initialize_environment(void)
>  		}
>
>  		if (pghost && pgport)
> -			printf(_("(using postmaster on %s, port %s)\n"), pghost, pgport);
> +			status(_("# (using postmaster on %s, port %s)\n"), pghost, pgport);
>  		if (pghost && !pgport)
> -			printf(_("(using postmaster on %s, default port)\n"), pghost);
> +			status(_("# (using postmaster on %s, default port)\n"), pghost);
>  		if (!pghost && pgport)
> -			printf(_("(using postmaster on Unix socket, port %s)\n"), pgport);
> +			status(_("# (using postmaster on Unix socket, port %s)\n"), pgport);
>  		if (!pghost && !pgport)
> -			printf(_("(using postmaster on Unix socket, default port)\n"));
> +			status(_("# (using postmaster on Unix socket, default port)\n"));
>  	}

It doesn't seem quite right to include the '# ' bit in the translated
string. If a translator were to not include it we'd suddenly have incorrect
tap output. That's perhaps not likely, but ... It's also not really necessary
to have it in as many translated strings?

Not that I understand why we even make these strings translatable. It seems
like it'd be a bad idea to translate this kind of output.

But either way, it seems nicer to output the # inside a helper function?

> +	/*
> +	 * In order for this information (or any error information) to be shown
> +	 * when running pg_regress test suites under prove it needs to be emitted
> +	 * stderr instead of stdout.
> +	 */
>  	if (file_size(difffilename) > 0)
>  	{
> -		printf(_("The differences that caused some tests to fail can be viewed in the\n"
> -				 "file \"%s\".  A copy of the test summary that you see\n"
> -				 "above is saved in the file \"%s\".\n\n"),
> +		status(_("\n# The differences that caused some tests to fail can be viewed in the\n"
> +				  "# file \"%s\".  A copy of the test summary that you see\n"
> +				  "# above is saved in the file \"%s\".\n\n"),
>  			   difffilename, logfilename);

The comment about needing to print to stderr is correct - but the patch
doesn't do so (anymore)?

The count of failed tests also should go to stderr (but not the report of all
tests having passed).

bail() probably also ought to print the error to stderr, so the most important
detail is immediately visible when looking at the failed test result.

Greetings,

Andres Freund

---

From: Dagfinn Ilmari Mannsåker <[email-masked]>
Date: Mon, 21 Nov 2022 13:42:25 +0000

> But either way, it seems nicer to output the # inside a helper function?

Note that the helper function should inject '# ' at the start of every
line in the message, not just the first line.  It might also be worth
having two separate functions: one that prints to stdout, so is only
shown by the harness is in verbose mode, and another which prints to
stderr, so is always shown.  Perl's Test::More calls these note() and
diag(), respectively.

> detail is immediately visible when looking at the failed test result.

Agreed on all three points.

> Andres Freund

- ilmari

---

From: Daniel Gustafsson <[email-masked]>
Date: Tue, 22 Nov 2022 23:17:44 +0100

> On 21 Nov 2022, at 14:42, Dagfinn Ilmari Mannsåker <[email-masked]> wrote:
> 

The attached v10 attempts to address the points raised above.  Notes and
diagnostics are printed to stdout/stderr respectively and the TAP emitter is
changed to move more of the syntax into it making it less painful on the
translators.

---

From: Andres Freund <[email-masked]>
Date: Tue, 22 Nov 2022 15:56:36 -0800

Hi,

> changed to move more of the syntax into it making it less painful on the

Thanks! I played a bit with it locally and it's nice.

I think it might be worth adding a few more details to the output on stderr,
e.g. a condensed list of failed tests, as that's then printed in the errorlogs
summary in meson after running all tests. As we don't do that in the current
output, that seems more like an optimization for later.

My compiler complains with:

[6/80 7   7%] Compiling C object src/test/regress/pg_regress.p/pg_regress.c.o
../../../../home/andres/src/postgresql/src/test/regress/pg_regress.c: In function ‘emit_tap_output_v’:
../../../../home/andres/src/postgresql/src/test/regress/pg_regress.c:354:9: warning: function ‘emit_tap_output_v’ might be a candidate for ‘gnu_printf’ format attribute [-Wsuggest-attribute=format]
  354 |         vfprintf(fp, fmt, argp);
      |         ^~~~~~~~
../../../../home/andres/src/postgresql/src/test/regress/pg_regress.c:356:17: warning: function ‘emit_tap_output_v’ might be a candidate for ‘gnu_printf’ format attribute [-Wsuggest-attribute=format]
  356 |                 vfprintf(logfile, fmt, argp_logfile);
      |                 ^~~~~~~~

Which seems justified and easily remedied via pg_attribute_printf().

I think there might be something slightly wrong with 'tags' - understandable,
since there's basically no comment explaining what it's supposed to do. I
added an intentional failure to 'show.pgc', which then yielded the following
tap output:
ok 51        sql/quote                                  15 ms
not ok 52    sql/show                                    9 ms
# tags: stdout source ok 53        sql/insupd                                 11 ms
ok 54        sql/parser                                 13 ms

which then subsequently leads meson to complain that
TAP parsing error: out of order test numbers
TAP parsing error: Too few tests run (expected 62, got 61)

Looks like all that's needed is a \n after "tags: %s"

I think the patch is also missing a \n after in log_child_failure().

If I kill postgres during a test I get:

# parallel group (12 tests):  regex tstypes geometry type_sanity misc_sanity horology expressions unicode mvcc opr_sanity comments xid
not ok 43           geometry                             8 ms
# (test process exited with exit code 2)not ok 44           horology                             9 ms
# (test process exited with exit code 2)not ok 45           tstypes                              7 ms
# (test process exited with exit code 2)not ok 46           regex                                7 ms

> Subject: [PATCH v10 2/2] Experimental: meson: treat regress tests as TAP

I'd just squash that in I think. Isn't really experimental either IMO ;)

> +static void
> +emit_tap_output_v(TAPtype type, const char *fmt, va_list argp)
> +{
> +	va_list		argp_logfile;
> +	FILE	   *fp = stdout;
> +
> +	/* We only need to copy the arg array in case we actually need it */
>  	if (logfile)
> -		fprintf(logfile, "\n");
> +		va_copy(argp_logfile, argp);
> +
> +	/*
> +	 * Diagnostic output will be hidden by prove unless printed to stderr.
> +	 * The Bail message is also printed to stderr to aid debugging under a
> +	 * harness which might otherwise not emit such an important message.
> +	 */
> +	if (type == DIAG || type == BAIL)
> +		fp = stderr;

Personally I'd move the initialization of fp to an else branch here, but
that's a very minor taste thing.

> +	/*
> +	 * Non-protocol output such as diagnostics or notes must be prefixed by
> +	 * a '#' character. We print the Bail message like this too.
> +	 */
> +	if (type == NOTE || type == DIAG || type == BAIL)
> +	{
> +		fprintf(fp, "# ");
> +		if (logfile)
> +			fprintf(logfile, "# ");
> +	}
> +	vfprintf(fp, fmt, argp);
> +	if (logfile)
> +		vfprintf(logfile, fmt, argp_logfile);
> +	/*
> +	 * If this was a Bail message, the bail protocol message must go to
> +	 * stdout separately.
> +	 */
> +	if (type == BAIL)
> +	{
> +		fprintf(stdout, "Bail Out!");
> +		if (logfile)
> +			fprintf(logfile, "Bail Out!");

I think this needs a \n.

> +	}
> +
> +	fflush(NULL);

I was wondering whether it's worth having an printf wrapper that does the
vfprintf(); if (logfile) vfprintf() dance. But it's proably not.

> @@ -1089,9 +1201,8 @@ spawn_process(const char *cmdline)
>  
>  		cmdline2 = psprintf("exec %s", cmdline);
>  		execl(shellprog, shellprog, "-c", cmdline2, (char *) NULL);
> -		fprintf(stderr, _("%s: could not exec \"%s\": %s\n"),
> -				progname, shellprog, strerror(errno));
> -		_exit(1);				/* not exit() here... */
> +		/* Not using the normal bail() here as we want _exit */
> +		_bail(_("could not exec \"%s\": %s\n"), shellprog, strerror(errno));
>  	}
>  	/* in parent */
>  	return pid;

Not in love with _bail, but I don't immediately have a better idea.

> @@ -1129,8 +1240,8 @@ file_size(const char *file)
>  
>  	if (!f)
>  	{
> -		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
> -				progname, file, strerror(errno));
> +		pg_log_error(_("# could not open file \"%s\" for reading: %s"),
> +					 file, strerror(errno));
>  		return -1;
>  	}
>  	fseek(f, 0, SEEK_END);

Hm. Shouldn't this just use diag()?

> @@ -1708,7 +1811,7 @@ run_schedule(const char *schedule, test_start_function startfunc,
>  				newdiff = results_differ(tests[i], rl->str, el->str);
>  				if (newdiff && tl)
>  				{
> -					printf("%s ", tl->str);
> +					appendStringInfo(&tagbuf, "%s ", tl->str);
>  				}
>  				differ |= newdiff;
>  			}
> @@ -1726,30 +1829,14 @@ run_schedule(const char *schedule, test_start_function startfunc,
>  						break;
>  					}
>  				}
> -				if (ignore)
> -				{
> -					status(_("failed (ignored)"));
> -					fail_ignore_count++;
> -				}
> -				else
> -				{
> -					status(_("FAILED"));
> -					fail_count++;
> -				}
> +
> +				test_status_failed(tests[i], ignore, tagbuf.data, INSTR_TIME_GET_MILLISEC(stoptimes[i]), (num_tests > 1));
>  			}
>  			else
> -			{
> -				status(_("ok    "));	/* align with FAILED */
> -				success_count++;
> -			}
> +				test_status_ok(tests[i], INSTR_TIME_GET_MILLISEC(stoptimes[i]), (num_tests > 1));
>  
>  			if (statuses[i] != 0)
> -
> -			INSTR_TIME_SUBTRACT(stoptimes[i], starttimes[i]);
> -
> -			status_end();

Hm. We probably shouldn't treat the test as a success if statuses[i] != 0?
Although it sure looks like we did so far.

>  		for (i = 0; i < num_tests; i++)
> @@ -1762,6 +1849,7 @@ run_schedule(const char *schedule, test_start_function startfunc,
>  		}
>  	}
>  
> +	pg_free(tagbuf.data);
>  	free_stringlist(&ignorelist);
>  
>  	fclose(scf);
> @@ -1785,11 +1873,12 @@ run_single_test(const char *test, test_start_function startfunc,
>  			   *el,
>  			   *tl;
>  	bool		differ = false;
> +	StringInfoData tagbuf;
>  
> -	status(_("test %-28s ... "), test);
>  	pid = (startfunc) (test, &resultfiles, &expectfiles, &tags);
>  	INSTR_TIME_SET_CURRENT(starttime);
>  	wait_for_tests(&pid, &exit_status, &stoptime, NULL, 1);
> +	initStringInfo(&tagbuf);
>
>  	/*
>  	 * Advance over all three lists simultaneously.
> @@ -1810,29 +1899,22 @@ run_single_test(const char *test, test_start_function startfunc,
>  		newdiff = results_differ(test, rl->str, el->str);
>  		if (newdiff && tl)
>  		{
> -			printf("%s ", tl->str);
> +			appendStringInfo(&tagbuf, "%s ", tl->str);

Why does tagbuf exist? Afaict it just is handed off 1:1 to test_status_failed?

While the above may sound like a fair bit of work, I think it's actually not
that much work, and we should strive to get this committed pretty soon!

Greetings,

Andres Freund

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 24 Nov 2022 15:24:21 +0100

> On 23 Nov 2022, at 00:56, Andres Freund <[email-masked]> wrote:

Thanks for testing and reviewing!

> output, that seems more like an optimization for later.

Since this patch already change the output verbosity it seems within the goal-
posts to do this now rather than later.  I've added a first stab at this in the
attached patch.

>  354 |         vfprintf(fp, fmt, argp);

Fixed.

> Looks like all that's needed is a \n after "tags: %s"

Ugh, yes, I forgot to run my ecpg tests before submitting. Fixed.

> I think the patch is also missing a \n after in log_child_failure().

Fixed.

> I'd just squash that in I think. Isn't really experimental either IMO ;)

Done.

> that's a very minor taste thing.

I actually had it like that before, moved it and wasn't sure what I preferred.
Moved back.

>> +			fprintf(logfile, "Bail Out!");

Fixed.

> vfprintf(); if (logfile) vfprintf() dance. But it's proably not.

Not sure if the saved lines of code justifies the loss of readability.

> Not in love with _bail, but I don't immediately have a better idea.

Agreed on both counts.

> Hm. Shouldn't this just use diag()?

It should.  I've changed all uses of pg_log_error to be diag or bail for
consistency in output, except for the one in getopt.

> Although it sure looks like we did so far.

Thats a good point, I admittedly hadn't thought about it.  55de145d1cf6f1d1b9
doesn't mention why it's done this way, maybe it's assumed that if the process
died then the test would've failed anyways (which is likely true but not
guaranteed to be so).

As it's unrelated to the question of output format I'll open a new thread with
that question to keep it from being buried here.

> Why does tagbuf exist? Afaict it just is handed off 1:1 to test_status_failed?

The relevant tags to print are collected in a StringInfo buffer in order to be
able to print them together with the failed status as they are only printed on
test failure.  Another option, which I tried in the attached version, could be
to print them the loop above as we do with parallel tests in wait_for_tests().
To keep it simple and not invent new code for this narrow usecase I opted for
the simple solution of one tag per diag line, like this:

# tag: stdout
# tag: source
not ok 52    sql/show                                  152 ms

I personally think thats fine, but it can be tweaked to print "# tags: stdout,
source" instead if we want to keep it closer to the current format.

> that much work, and we should strive to get this committed pretty soon!

The attached v11 fixes the above and have had a pgindent run on it as it's
hopefully getting close to done. Thanks again for reviewing!

---

From: Nikolay Shaplov <[email-masked]>
Date: Thu, 24 Nov 2022 20:07:29 +0300

You guys are really fast... I only think about problem, it is already 
mentioned here... Most issues I've noticed are already fixed before I was able 
to say something. 

Nevertheless...

 /*                                                                              
  * Bailing out is for unrecoverable errors which prevents further testing to    
  * occur and after which the test run should be aborted. By passing non_rec     
  * as true the process will exit with _exit(2) and skipping registered exit     
  * handlers.                                                                    
  */                                                                             
 static void                                                                     
 bail_out(bool non_rec, const char *fmt,...)                                     
 {                                               

In original code, where _exit were called, there were mention about recursion 
(whatever it is) as a reason for using _exit() instead of exit(). Now this 
mention is gone:

-           _exit(2);           /* not exit(), that could be recursive */
+           /* Not using the normal bail() as we want _exit */
+           _bail(_("could not stop postmaster: exit code was %d\n"), r);

The only remaining part of recursion is _rec suffix.

I guess we should keep mention of recursion in comments, and for me _rec 
stands for "record", not "recursion", I will not guess original meaning by 
_rec suffix. I would suggest to change it to _recurs or _recursive to keep 
things clear

-----

+#define _bail(...)	bail_out(true, __VA_ARGS__)
+#define bail(...)	bail_out(false, __VA_ARGS__)

I will never guess what the difference between bail, _bail and bail_out. We 
need really good explanation here, or better to use self-explanatory names 
here... 

I would start bail_out with _ as it is "internal", not used in the code.
And for _bail I would try to find some name that shows it's nature. Like 
bail_in_recursion or something.

-----

+   if (ok || ignore)
    {
-       va_start(ap, fmt);
-       vfprintf(logfile, fmt, ap);
-       va_end(ap);
+       emit_tap_output(TEST_STATUS, "ok %-5i     %s%-*s %8.0f ms%s\n",
+                       testnumber,
+                       (parallel ? PARALLEL_INDENT : ""),
+                       padding, testname,
+                       runtime,
+                       (ignore ? " # SKIP (ignored)" : ""));
+   }
+   else
+   {
+       emit_tap_output(TEST_STATUS, "not ok %-5i %s%-*s %8.0f ms\n",
+                       testnumber,
+                       (parallel ? PARALLEL_INDENT : ""),
+                       padding, testname,
+                       runtime);
    }

This magic spell "...%-5i %s%-*s %8.0f ms\n" is too dark to repeat it even two 
times. I understand problems with spaces... But may be it would be better 
somehow narrow it to one ugly print... Print "ok %-5i    "|"not ok %-5i" to 
buffer first, and then have one "%s%-*s %8.0f ms%s\n" print or something like 
that...

I am not strongly insisting on that, but I feel strong urge to remove code 
duplication here...

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 24 Nov 2022 20:07:43 +0100

> On 24 Nov 2022, at 18:07, Nikolay Shaplov <[email-masked]> wrote:
> 

Thanks for looking and reviewing!

> _rec suffix. I would suggest to change it to _recurs or _recursive to keep 

The other original comment on _exit usage reads:

	/* not exit() here... */

I do think that the longer explanation I added in the comment you quoted above
is more explanatory than those.  I can however add a small note on why skipping
registered exit handlers is useful (ie, not risk recursive calls to exit()).

> bail_in_recursion or something.

One option could be to redefine bail() to take the exit function as a parameter
and have the caller pass the preferred exit handler.

-bail_out(bool non_rec, const char *fmt,...)
+bail(void (*exit_func)(int), const char *fmt,...)

The callsites would then look like the below, which puts a reference to the
actual exit handler used in the code where it is called.  I find it a bit
uglier, but also quite self-explanatory:

@@ -409,10 +403,7 @@ stop_postmaster(void)
                fflush(NULL);
                r = system(buf);
                if (r != 0)
-               {
-                       /* Not using the normal bail() as we want _exit */
-                       _bail(_("could not stop postmaster: exit code was %d\n"), r);
-               }
+                       bail(_exit, _("could not stop postmaster: exit code was %d\n"), r);

                postmaster_running = false;
        }
@@ -469,7 +460,7 @@ make_temp_sockdir(void)
        temp_sockdir = mkdtemp(template);
        if (temp_sockdir == NULL)
        {
-               bail(_("could not create directory \"%s\": %s\n"),
+               bail(exit, _("could not create directory \"%s\": %s\n"),
                         template, strerror(errno));
        }

Not sure what is the best option, but I've been unable to think of a name which
is documenting the code well enough that a comment explaining why isn't
required.

> buffer first, and then have one "%s%-*s %8.0f ms%s\n" print or something like 

I'm not convinced that this printf format is that hard to read (which may well
be attributed to Stockholm Syndrome), and I do think that breaking it up and
adding more code to print the line will make it less readable instead.

---

From: Andres Freund <[email-masked]>
Date: Thu, 24 Nov 2022 11:32:35 -0800

On November 24, 2022 11:07:43 AM PST, Daniel Gustafsson <[email-masked]> wrote:
>actual exit handler used in the code where it is called.

I'd just rename _bail to bail_noatexit().

>adding more code to print the line will make it less readable instead.

I don't think it's terrible either. I do think it'd also be ok to switch between ok / not ok within a single printf, making it easier to keep them in sync.

Andres

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.

---

From: Daniel Gustafsson <[email-masked]>
Date: Thu, 24 Nov 2022 22:20:01 +0100

> On 24 Nov 2022, at 20:32, Andres Freund <[email-masked]> wrote:
> 

That's probably the best option, done in the attached along with the comment
fixup to mention the recursion issue.

> I don't think it's terrible either. I do think it'd also be ok to switch between ok / not ok within a single printf, making it easier to keep them in sync.

I made it into a single printf to see what it would look like, with some
additional comments to make it more readable (I'm not a fan of where pgindent
moves those but..).

---

From: Nikolay Shaplov <[email-masked]>
Date: Sat, 26 Nov 2022 22:37:08 +0300

В письме от пятница, 25 ноября 2022 г. 00:20:01 MSK пользователь Daniel 
Gustafsson написал:

+ /*                                                                              
+  * The width of the testname field when printing to ensure vertical 
alignment   
+  * of test runtimes. Thius number is somewhat arbitrarily chosen to match 
the   
+  * older pre-TAP output format.                                                 
+  */

"Thius" seems to be a typo :-)

-----

+ #define bail_noatexit(...)  bail_out(true, __VA_ARGS__)

BTW what does "noat" stands for? I thought it is typo too :-) and originally 
meant to be "not". 

-----

-       snprintf(buf, sizeof(buf),
-                _(" All %d tests passed. "),
-                success_count);
-   else if (fail_count == 0)   /* fail_count=0, fail_ignore_count>0 */
-       snprintf(buf, sizeof(buf),
-                _(" %d of %d tests passed, %d failed test(s) ignored. "),
-                success_count,
-                success_count + fail_ignore_count,
-                fail_ignore_count);
-   else if (fail_ignore_count == 0)    /* fail_count>0 && fail_ignore_count=0 
*/
-       snprintf(buf, sizeof(buf),
-                _(" %d of %d tests failed. "),
-                fail_count,
-                success_count + fail_count);
+       note(_("All %d tests passed.\n"), success_count);
+   /* fail_count=0, fail_ignore_count>0 */
+   else if (fail_count == 0)
+       note(_("%d of %d tests passed, %d failed test(s) ignored.\n"),
+            success_count,
+            success_count + fail_ignore_count,
+            fail_ignore_count);
+   /* fail_count>0 && fail_ignore_count=0 */
+   else if (fail_ignore_count == 0)
+       diag(_("%d of %d tests failed.\n"),
+            fail_count,
+            success_count + fail_count);
+   /* fail_count>0 && fail_ignore_count>0 */

Just out of overaccuracy:  Logic here have not changed. Can we keep ifs, elses 
and may be indent offsets of lines that did not change as they were to have 
nicer diff? Would make understanding this changeset more easy... Or this is 
work of pg_indent that spoils it?

----

While looking at the my output I am getting wrong offset for 
sanity_check:

ok 84               hash_func                          121 ms
ok 85               errors                              68 ms
ok 86               infinite_recurse                   233 ms
ok 87        sanity_check                              144 ms
# parallel group (20 tests):  select_into delete random select_having 
select_distinct_on namespace select_implicit case prepared_xacts subselect 
transactions portals select_distinct union arrays update hash_index join 
aggregates btree_index
ok 88               select_into                        134 ms
ok 89               select_distinct                    812 ms

(also for select_parallel write_parallel vacuum_parallel and fast_default)

I guess the intention was to align them too...

----

As for the rest: I see no other problems in the code, and consider it should 
be passed to commiter (or may be more experienced reviewer)

> >> One option could be to redefine bail() to take the exit function as a
> >> parameter and have the caller pass the preferred exit handler.
> >> 
> >>> This magic spell "...%-5i %s%-*s %8.0f ms\n" is too dark to repeat it
> >>> even two times. I understand problems with spaces... But may be it
> >>> would be better somehow narrow it to one ugly print... Print "ok %-5i  
> >>>  "|"not ok %-5i" to buffer first, and then have one "%s%-*s %8.0f
> >>> ms%s\n" print or something like that...
> >> 
> >> I'm not convinced that this printf format is that hard to read (which may
> >> well be attributed to Stockholm Syndrome), and I do think that breaking
> >> it up and adding more code to print the line will make it less readable
> >> instead.> 
> > I don't think it's terrible either. I do think it'd also be ok to switch
> > between ok / not ok within a single printf, making it easier to keep them
> > in sync.
> additional comments to make it more readable (I'm not a fan of where
> pgindent moves those but..).
> 
> --

---

From: Daniel Gustafsson <[email-masked]>
Date: Sat, 26 Nov 2022 21:35:45 +0100

> On 26 Nov 2022, at 20:37, Nikolay Shaplov <[email-masked]> wrote:

> "Thius" seems to be a typo :-)

Correct, fixed in the attached.

> BTW what does "noat" stands for? I thought it is typo too :-) and originally 

Calling _exit() will cause exit handler functions registered with atexit() to
not be invoked, no noatexit was intentional spelling.

> work of pg_indent that spoils it?

The diff algorithm decided that this was the compact way of displaying the
unified diff, probably because too many lines in proximity changed.  While
avoiding moving the comments to before the line might mitigate that somewhat I
prefer this greatly to a slightly easier to read diff.

> I guess the intention was to align them too...

No, they are aligned in such a way because they are running outside of a
parallel group.  Note that it's not part of the "parallel group" note
preceeding the tests:

# parallel group (6 tests):  collate.linux.utf8 amutils psql_crosstab psql rules stats_ext
ok 146              rules                              507 ms
ok 147              psql                               448 ms
ok 148              psql_crosstab                       47 ms
ok 149              amutils                             39 ms
ok 150              stats_ext                         2578 ms
ok 151              collate.linux.utf8                  27 ms
ok 152       select_parallel                           668 ms
ok 153       write_parallel                             84 ms
ok 154       vacuum_parallel                            90 ms

In the previous format it's a bit clearer, and maybe we should adopt that for
TAP as well?

parallel group (6 tests):  collate.linux.utf8 amutils psql_crosstab psql rules stats_ext
     rules                        ... ok          488 ms
     psql                         ... ok          430 ms
     psql_crosstab                ... ok           47 ms
     amutils                      ... ok           38 ms
     stats_ext                    ... ok         2301 ms
     collate.linux.utf8           ... ok           24 ms
test select_parallel              ... ok          641 ms
test write_parallel               ... ok           83 ms
test vacuum_parallel              ... ok           87 ms

That would if so make the output something like the below.  Personally I think
the "test" prefix adds little value since everything printed are test suites,
and we are already today using indentation for grouping parallel tests.

# parallel group (6 tests):  collate.linux.utf8 amutils psql_crosstab psql rules stats_ext
ok 146              rules                              507 ms
ok 147              psql                               448 ms
ok 148              psql_crosstab                       47 ms
ok 149              amutils                             39 ms
ok 150              stats_ext                         2578 ms
ok 151              collate.linux.utf8                  27 ms
ok 152       test select_parallel                      668 ms
ok 153       test write_parallel                        84 ms
ok 154       test vacuum_parallel                       90 ms

---

From: Nikolay Shaplov <[email-masked]>
Date: Sun, 27 Nov 2022 13:22:58 +0300

В письме от суббота, 26 ноября 2022 г. 23:35:45 MSK пользователь Daniel 
Gustafsson написал:
> > BTW what does "noat" stands for? I thought it is typo too :-) and
> > originally meant to be "not".
> 
> Calling _exit() will cause exit handler functions registered with atexit()
> to not be invoked, no noatexit was intentional spelling.

I've read some mans:

The function _exit() terminates the calling process "immediately".

I guess, "immediately" is a good word here that very precisely describes what 
is happening here. 

I wold suggest to use word immediate instead of noatexit. This will do the 
code much more sensible for me. 

-------
/*
 * Bailing out is for unrecoverable errors which prevents further testing to
 * occur and after which the test run should be aborted. By passing immediate
 * as true the process will terminate process with _exit() instead of exit().
 * This will allow to skip registered exit handlers, thus avoid possible
 * infinite recursive calls while exiting.
 */
static void
bail_out(bool immediate, const char *fmt,...)
{
        va_list         ap;

        va_start(ap, fmt);
        emit_tap_output_v(BAIL, fmt, ap);
        va_end(ap);

        if (immediate)
                _exit(2);

        exit(2);
}

#define bail_immediate(...)     bail_out(true, __VA_ARGS__)
#define bail(...)                       bail_out(false, __VA_ARGS__)
-------

I've also rewritten the comment, the way I would understand it better, if I 
read it for the first time. I am not sure about my English, but key features 
there are: 

- "terminate process" instead of "exit". Too many exist in the sentence, 
better to use synonyms wherever is possible.
- "_exit() instead of exit()" more accurate description of what is happening 
here
- Split this sentence into two. First sentence: what does it do. Second 
sentence: why it does so.
- Added "infinite" word before "recursion". Recursion is not a bad thing, 
infinite recursion is. This explicitly state what we are trying to avoid.

======

> unified diff, probably because too many lines in proximity changed.
When line is not changed it is never added to a change block by diff... I 
guess this part should be looking like that:

-               snprintf(buf, sizeof(buf),
-                                _(" All %d tests passed. "),
+			      note(_("All %d tests passed.\n"), 
                                success_count);
       else if (fail_count == 0)       /* fail_count=0, fail_ignore_count>0 */
-               snprintf(buf, sizeof(buf),
-                                _(" %d of %d tests passed, %d failed test(s) 
ignored. "),
+               note(_("%d of %d tests passed, %d failed test(s) ignored.\n"),
                                success_count,
                                success_count + fail_ignore_count,
                                fail_ignore_count);
       else if (fail_ignore_count == 0)        /* fail_count>0 && 
fail_ignore_count=0 */
-               snprintf(buf, sizeof(buf),
-                                _(" %d of %d tests failed. "),
+               diag(_("%d of %d tests failed.\n"),
                                fail_count,
                                success_count + fail_count);

Working with my students I usually insist them to provide such patches.
 
> While
> avoiding moving the comments to before the line might mitigate that somewhat
> I prefer this greatly to a slightly easier to read diff.

I do not quite understand what are you trying to achieve here, what stands 
behind "prefer", but if it is important for you, I will no longer insist.

===== 

> That would if so make the output something like the below.  Personally I
> think the "test" prefix adds little value since everything printed are test
> suites, and we are already today using indentation for grouping parallel
> tests.

So this extra offset indicates that test is being included into parallel 
group? Guess it not really obvious...

I am not sure I have a clear idea what can be done here.

May be it some ideal I would give each group a name. Like

ok 8                types.int2                                45 ms
ok 9                types.int4                                73 ms
ok 10               types.int8                                91 ms
ok 11               types.oid                                 47 ms
ok 12               types.float4                              88 ms
ok 13               types.float8                             139 ms
ok 14               types.bit                                165 ms
ok 15               types.numeric                           1065 ms

but this does not seems very realistic in the current code base and the scope 
of this path.

Theoretically TAP 14 has subtests and this parallel tests looks like 
subtests... but TAP 14 is not supported by modern harnesses..

So I have no idea...
May be leaving it as it is for now, is good enough...

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 28 Nov 2022 14:13:16 +0100

> On 27 Nov 2022, at 11:22, Nikolay Shaplov <[email-masked]> wrote:

> code much more sensible for me. 

I think noatexit is clearer since the codepath is specifically to avoid any
registered atexit functions.  The point of this function is to be able to call
bail while in a function registered with atexit() so I think the current name
is better.

> better to use synonyms wherever is possible.

Sure, I can do that before pushing if the current version of the patch is
acceptable.

> group? Guess it not really obvious...

Grouping parallel tests via an initial list of test and then indenting each
test with whitespace was committed 22 years ago.  While there might be better
ways to do this, the lack of complaints so far at least seems to indicate that
it isn't all too terrible.

> subtests... but TAP 14 is not supported by modern harnesses..

Parallel tests aren't subtests though, they are single top-level tests which
run in parallel to each other.

---

From: Andres Freund <[email-masked]>
Date: Mon, 28 Nov 2022 10:28:48 -0800

+1

---

From: Nikolay Shaplov <[email-masked]>
Date: Mon, 28 Nov 2022 22:02:38 +0300

В письме от понедельник, 28 ноября 2022 г. 21:28:48 MSK пользователь Andres 
Freund написал:
> > registered atexit functions.  The point of this function is to be able to
> > call bail while in a function registered with atexit() so I think the
> > current name is better.
> 
> +1

Ok, then I would not insist on it.

> ways to do this, the lack of complaints so far at least seems to indicate
> that it isn't all too terrible.

Ok, it was there for 22 years, it will do no harm if it is left this way for 
some time :-)

----

From my reviewer's point of view patch is ready for commit.

Thank you for your patience :-)

PS Should I change commitfest status?

---

From: Daniel Gustafsson <[email-masked]>
Date: Mon, 28 Nov 2022 20:27:02 +0100

> On 28 Nov 2022, at 20:02, Nikolay Shaplov <[email-masked]> wrote:

> Thank you for your patience :-)

Thanks for review.

The attached tweaks a few comments and attempts to address the compiler warning
error in the CFBot CI.  Not sure I entirely agree with the compiler there but
here is an attempt to work around it at least (by always copying the va_list
for the logfile). It also adds a missing va_end for the logfile va_list.

I hope this is close to a final version of this patch (commitmessage needs a
bit of work though).

> PS Should I change commitfest status?

Sure, go ahead.