Skip to content

Take a decimal scale into account - #1925

Merged
YohDeadfall merged 10 commits into
npgsql:devfrom
StillLearnin:dev
May 15, 2018
Merged

YohDeadfall merged 10 commits into
npgsql:devfrom
StillLearnin:dev

Conversation

@StillLearnin

Copy link
Copy Markdown
Contributor

No description provided.

@StillLearnin

Copy link
Copy Markdown
Contributor Author

@roji @YohDeadfall I think this is ready to merge unless you have some suggestions or corrections. Any thoughts?

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this precise work @StillLearnin. As I noted in the comments, I don't think it's acceptable perf-wise for the handler to allocate when reading every single decimal (decimalGetBits()). A minor CPU processing cost is OK - even if the perf cost of the new Math.Pow() and Math.Round(ModpointRounding.AwayFromZero) needs to be measured - but allocations have a much higher impact on general application performance, since they create GC pressure.

If this were really necessary for correctness, that's one thing. However, here we're proposing an allocation on every decimal read just in order to have the proper number of zeros, which is mainly important for display purposes - so I'm not very happy with that.

You may be able to eliminate the GetBits() call by looking at the type modifier as I previously proposed, I'm not sure. But I'd like to avoid the allocations in the current state of this PR.

//midpoint rounding is AwayFromZero instead of ToEven https://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx
//This is necessary to match psql.
var rounding = new Tuple<string, decimal>[] {
new Tuple<string,decimal>("'1'::numeric(10,2)", 1.00M), //test scale

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test needs to be cleaned up and possibly split into several ones... It starts with a check on 1234567.890123 that is very similar to what you've added here (so the two need to be merged).

Instead of having an array of Tuple, it's better to have a separate test with TestCases (see

[Test, Description("Checks several scenarios in which the SQL is supposed to pass untouched")]
for an example).

Also, in general the Tuple class is a little obsolete ever since C# 7 introduced value tuples with integrated syntax in C#.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good points, I can do that.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: spaces after commas

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@YohDeadfall sure enough! Can hardly believe I missed that. At first I thought you meant there shouldn't be spaces after commas...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@roji I have a little time today after all. Does the latest commit of tests seem acceptable?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it same as NumericScaleCasting? If yes, remove it.

throw new NpgsqlSafeReadException(new InvalidCastException("Numeric NaN not supported by System.Decimal"));

result = Math.Round(result, dscale);
var rscale = ((decimal.GetBits(result)[3] >> 16) & 0x7F); //Find scale of result

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

decimal.GetBits() always allocates an int[], which is really not good.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you have a suggestion on a better way to do it? See my other comments (coming soon) on why I believe trailing zeros aren't just a cosmetic issue.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use the following struct to store result and to do dirty magic:

[StructLayout(LayoutKind.Explicit)]
ref struct DecimalRaw
{
    internal const int SignMask = unchecked((int)0x80000000);
    internal const int ScaleMask = 0x00FF0000;
    internal const int ScaleShift = 16;

    [FieldOffset(0)]
    internal decimal Value;

    [FieldOffset(0)]
    internal int Flags;
    [FieldOffset(4)]
    internal int Hi;
    [FieldOffset(8)]
    internal int Lo;
    [FieldOffset(12)]
    internal int Mid;
}
var rscale = (result.Flags & DecimalRaw.ScaleMask) >> DecimalRaw.ScaleShift;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@YohDeadfall I assume you're recommending a struct for result storage because it will be stored on the stack instead of the heap. This allows us to read the result scale which is then stored in rscale, also on the stack as a simple integer value.

Since popping the stack is much faster than garbage collection, we avoid a lot of overhead.

Did I get it right?

P.S. Most of my work has not needed to be so performance critical so I'm still learning this stuff.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, you're right, except one thing. Overhead is not in popping, but in memory allocation on the heap. GetBits allocates an array of four integers.

Don't worry about that. I'll help you with perf optimizations.

@StillLearnin StillLearnin May 14, 2018 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't the FieldOffset for Mid and Lo be

    [FieldOffset(8)]
    internal int Mid;
    [FieldOffset(12)]
    internal int Lo;

Instead of

    [FieldOffset(8)]
    internal int Lo;
    [FieldOffset(12)]
    internal int Mid;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, the order is defined in coreclr (source).

var rscale = ((decimal.GetBits(result)[3] >> 16) & 0x7F); //Find scale of result

if (rscale < dscale) //If result scale is insufficient,
result = result * new decimal((int)Math.Pow(10, dscale), 0, 0, false, 2); //increase it.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So in the end we don't have to look at the type modifier to know what scale to round to?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is right. My original understanding that dscale was the scale of the data rather than the scale of the column was incorrect.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Math.Pow is a perf killer. Use a table of predefined values (powers of 10).

static readonly decimal[] Powers10 =
{
    1M,
    10M,
    100M,
    1000M,
    10000M,
    100000M,
    1000000M,
    10000000M,
    100000000M,
    1000000000M,
    10000000000M,
    // And so on. You should totally have 29 powers of 10.
};
result.Value *= new DecimalRaw { Value = Powers10[scale - resultScale], Flags = (scale - resultScale) << DecimalRaw.ScaleShift }.Value;

It's okay to have 1000000000 as the max value in the table and to store ints in it, but then you should implement a method to produce a DecimalRaw value with the required scale.

@StillLearnin

StillLearnin commented May 11, 2018 •

Copy link
Copy Markdown
Contributor Author

If this were really necessary for correctness, that's one thing. However, here we're proposing an allocation on every decimal read just in order to have the proper number of zeros, which is mainly important for display purposes

I respectfully disagree. decimal is a type with 28 - 29 significant digits. Significant digits (which include trailing zeros in the decimal portion) are important in mathematical calculations and are used to specify exactly to what scale the measurement was done. If an actual value of 1.2 is stored in a column that has a scale of 2, that means the data is assumed to be verified to be 1.20 and we should return 1.20 not 1.2 or 1.2000 even though the values are the same. The whole point of decimal is to have a type that can reliably express precision/scale.

Without this fix or a better one, it is impossible to use postgresql's cast methods. For instance, SELECT '1.2'::numeric(10,2) does not work without this fix.

This was the simplest method for consistently achieving the correct result that I could come up with in the amount of time I had available. It could probably be improved in terms of performance. @YohDeadfall do you have time to weigh in with a benchmark? I won't have time to work on this till next week.

@roji

roji commented May 11, 2018

Copy link
Copy Markdown
Member

I'm sorry this is more complicated than it seemed (and I appreciate your work), I'm not trying to complicate the situation or prevent improvements - just make sure the right decisions are being made as a whole.

If this were really necessary for correctness, that's one thing. However, here we're proposing an allocation on every decimal read just in order to have the proper number of zeros, which is mainly important for display purposes

I respectfully disagree. decimal is a type with 28 - 29 significant digits. Significant digits (which include trailing zeros in the decimal portion) are important in mathematical calculations and are used to specify exactly to what scale the measurement was done. If an actual value of 1.2 is stored in a column that has a scale of 2, that means the data is assumed to be verified to be 1.20 and we should return 1.20 not 1.2 or 1.2000 even though the values are the same. The whole point of decimal is to have a type that can reliably express precision/scale.

That's an interesting and valid point, at least for some use cases of decimal/numeric. I'd venture to say that in most scenarios trailing zeros aren't actually important - but that's just my unfounded opinion (the main supporting fact is that people have hardly complained up to now). The main point of decimal IMHO is more to produce 100% accurate calculations, avoiding the pitfalls that floating-point arithmetic introduce (e.g. in monetary calculations), rather than preserving trailing zeros. It could also be claimed that the user should know the "verified" scale since they created the PostgreSQL column with a given scale, or if they don't, they can look at the column's datatype and find out from there.

On the other hand, to argue against myself, C# decimal does preserve trailing zeros (unlike double), so that supports your point of view.

But in any case, I do agree that there's value in preserving trailing zeros based on the column definition - the only question is perf cost. My problem is not really with CPU perf (i.e. the Math.Pow() and Math.Round() calls) but rather with the allocation - in my opinion adding an allocation to the decoding of each and every decimal isn't acceptable; it would mean penalizing all users of decimal just so that the cases where trailing zeros are important would be handled.

I don't have a lot of time to look into avoiding this, but the answer is likely that we shouldn't parse the PostgreSQL data in the first loop, and then try to apply scale properly. Instead, the required scale should probably be taken into account in the loop, as you're parsing the PostgreSQL data.

Hopefully someone will have a bit of time to invest on this, otherwise I might be able to take a look at some point (but not necessarily for 4.0).

@roji

roji commented May 11, 2018

Copy link
Copy Markdown
Member

Another direction is to look at how PostgreSQL itself decodes decimal in C and see what we can learn from that.

@StillLearnin

Copy link
Copy Markdown
Contributor Author

No problem. A discussion like this is important to keep the code from becoming bloated and slow. I'm new to this project and you have a significant amount of time invested into it. I'm not offended at your slowness to "just accept" code from someone you've never met and haven't yet had the opportunity to build confidence in.

the answer is likely that we shouldn't parse the PostgreSQL data in the first loop, and then try to apply scale properly. Instead, the required scale should probably be taken into account in the loop, as you're parsing the PostgreSQL data

This is precisely where my mind was going and several times in my research into this topic I almost tackled it that way. I'll try to look into it next week.

@roji

roji commented May 11, 2018

Copy link
Copy Markdown
Member

Thanks for your understanding...

One of the primary focuses of 4.0 is performance (it even got a mention in Build a couple days ago) so I'm particularly careful with that. There's also a clear, growing realization of the adverse perf impact of heap allocations and the importance of keeping them down as much as possible.

This is precisely where my mind was going and several times in my research into this topic I almost tackled it that way. I'll try to look into it next week.

OK great, good luck. The RTM release isn't supposed to happen until at least the end of the month so there's still time.

@StillLearnin

Copy link
Copy Markdown
Contributor Author

Congrats on the positive reference at build!

throw new NpgsqlSafeReadException(new InvalidCastException("Numeric NaN not supported by System.Decimal"));

result = Math.Round(result, dscale);
var rscale = ((decimal.GetBits(result)[3] >> 16) & 0x7F); //Find scale of result

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use the following struct to store result and to do dirty magic:

[StructLayout(LayoutKind.Explicit)]
ref struct DecimalRaw
{
    internal const int SignMask = unchecked((int)0x80000000);
    internal const int ScaleMask = 0x00FF0000;
    internal const int ScaleShift = 16;

    [FieldOffset(0)]
    internal decimal Value;

    [FieldOffset(0)]
    internal int Flags;
    [FieldOffset(4)]
    internal int Hi;
    [FieldOffset(8)]
    internal int Lo;
    [FieldOffset(12)]
    internal int Mid;
}
var rscale = (result.Flags & DecimalRaw.ScaleMask) >> DecimalRaw.ScaleShift;

var rscale = ((decimal.GetBits(result)[3] >> 16) & 0x7F); //Find scale of result

if (rscale < dscale) //If result scale is insufficient,
result = result * new decimal((int)Math.Pow(10, dscale), 0, 0, false, 2); //increase it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Math.Pow is a perf killer. Use a table of predefined values (powers of 10).

static readonly decimal[] Powers10 =
{
    1M,
    10M,
    100M,
    1000M,
    10000M,
    100000M,
    1000000M,
    10000000M,
    100000000M,
    1000000000M,
    10000000000M,
    // And so on. You should totally have 29 powers of 10.
};
result.Value *= new DecimalRaw { Value = Powers10[scale - resultScale], Flags = (scale - resultScale) << DecimalRaw.ScaleShift }.Value;

It's okay to have 1000000000 as the max value in the table and to store ints in it, but then you should implement a method to produce a DecimalRaw value with the required scale.

//midpoint rounding is AwayFromZero instead of ToEven https://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx
//This is necessary to match psql.
var rounding = new Tuple<string, decimal>[] {
new Tuple<string,decimal>("'1'::numeric(10,2)", 1.00M), //test scale

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: spaces after commas

@YohDeadfall YohDeadfall changed the title Tests to ensure decimal scale is correctly handled. Fixes #1921 Take a decimal scale into account May 11, 2018
{
using (var conn = OpenConnection())
{
using (var cmd = new NpgsqlCommand($"SELECT {sql}", conn))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can write the first using without curly brackets to decrease indentation.

using (var conn = OpenConnection())
using (var cmd = new NpgsqlCommand($"SELECT {sql}", conn))
{
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good point.

[TestCase("'-1.5'::numeric(10,0)", "-2", TestName = "RoundNegativeOddUp")]
[TestCase("'-2.4'::numeric(10,0)", "-2", TestName = "RoundNegativeEvenDown")]
[TestCase("'-2.5'::numeric(10,0)", "-3", TestName = "RoundNegativeEvenUp")]
public void NumericScaleCasting(string sql, string expected)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason for expected to be a string instead of a decimal directly?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup. decimal is not a constant type and can't be used where a constant expression is required.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do you mean? You can have decimal literals with m, and the compiler seems to accept [TestCase(8m)] just fine...

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@roji Nope, it will cause CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type. It's not a primitive type.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry about that, no red squgglies in Rider for some reason but you're right that it doesn't compile. Here's an article by Jon Skeet that goes a bit deep into this.

@StillLearnin

Copy link
Copy Markdown
Contributor Author

The RTM release isn't supposed to happen until at least the end of the month

@roji Is that Npgsql 4.0 you're talking about? Is there a list of what's to be done yet?

@roji

roji commented May 14, 2018

Copy link
Copy Markdown
Member

@StillLearnin yep, the 4.0 RTM. The idea is to release at the same time as Microsoft releases 2.1 (.NET Core, Entity Framework Core), which should be around the end of the month, maybe a bit later.

There isn't a huge amount to be done, you can take a look at the issue list. Aside from two somewhat large things, the idea is to stabilize and fix bugs (we did release an RC after all).

@YohDeadfall YohDeadfall left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. Please add a benchmark to the PR and post results for the code before your changes and after. For example see GetFieldValue in Npgsql.Benchmarks.

var overflow = false;

var result = 0M;
var result = new DecimalRaw() { Value = 0M };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can remove { Value = 0M } because it's already initialized to 0. Use new DecimalRaw() or default(DecimalRaw).

@StillLearnin

Copy link
Copy Markdown
Contributor Author

@YohDeadfall ready for you to perf test.
@roji build failed on travis but doesn't appear to be my problem.

@StillLearnin

StillLearnin commented May 14, 2018 •

Copy link
Copy Markdown
Contributor Author

Please add a benchmark to the PR and post result for the code before your changes and after. For example see GetFieldValue in Npgsql.Benchmarks.

@YohDeadfall thanks for the pointer. Will do.

@StillLearnin

Copy link
Copy Markdown
Contributor Author

Benchmark

    [Config(typeof(Config))]
    public class NumericPerf
    {
        readonly NpgsqlConnection _conn;
        readonly NpgsqlCommand _cmd;
        readonly NpgsqlDataReader _reader;

        public NumericPerf()
        {
            _conn = BenchmarkEnvironment.OpenConnection();
            _cmd = new NpgsqlCommand("SELECT '1.25'::numeric(10,1), '1.24'::numeric(10,1), '1.2'::numeric(10,2), '1.2'::numeric(10,3), '1.2'::numeric(10,4), '1.2'::numeric(10,5)", _conn);
            _reader = _cmd.ExecuteReader();
            _reader.Read();
        }

        [Benchmark]
        public void RoundUp() => _reader.GetFieldValue<decimal>(0);

        [Benchmark]
        public void RoundDown() => _reader.GetFieldValue<decimal>(1);

        [Benchmark]
        public void ExpandScale2() => _reader.GetFieldValue<decimal>(2);

        [Benchmark]
        public void ExpandScale3() => _reader.GetFieldValue<decimal>(3);

        [Benchmark]
        public void ExpandScale4() => _reader.GetFieldValue<decimal>(4);

        [Benchmark]
        public void ExpandScale5() => _reader.GetFieldValue<decimal>(5);

        class Config : ManualConfig
        {
            public Config() => Add(StatisticColumn.OperationsPerSecond);
        }
    }

Before

BenchmarkDotNet=v0.10.14, OS=Windows 10.0.16299.431 (1709/FallCreatorsUpdate/Redstone3)
Intel Core i7-4720HQ CPU 2.60GHz (Haswell), 1 CPU, 8 logical and 4 physical cores
Frequency=2533212 Hz, Resolution=394.7557 ns, Timer=TSC
  [Host]     : .NET Framework 4.6.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2650.0  [AttachedDebugger]
  DefaultJob : .NET Framework 4.6.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2650.0

Method Mean Error StdDev Op/s
RoundUp 192.5 ns 0.7644 ns 0.6776 ns 5,193,795.3
RoundDown 193.5 ns 1.0655 ns 0.8897 ns 5,169,159.4
ExpandScale2 190.6 ns 0.5890 ns 0.5221 ns 5,246,641.0
ExpandScale3 192.7 ns 1.5666 ns 1.3082 ns 5,188,141.1
ExpandScale4 162.3 ns 0.5285 ns 0.4126 ns 6,162,913.0
ExpandScale5 164.7 ns 1.4995 ns 1.4026 ns 6,070,534.1

After

BenchmarkDotNet=v0.10.14, OS=Windows 10.0.16299.431 (1709/FallCreatorsUpdate/Redstone3)
Intel Core i7-4720HQ CPU 2.60GHz (Haswell), 1 CPU, 8 logical and 4 physical cores
Frequency=2533212 Hz, Resolution=394.7557 ns, Timer=TSC
  [Host]     : .NET Framework 4.6.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2650.0  [AttachedDebugger]
  DefaultJob : .NET Framework 4.6.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2650.0

Method Mean Error StdDev Op/s
RoundUp 181.4 ns 2.1687 ns 1.8110 ns 5,513,180.4
RoundDown 181.0 ns 0.9125 ns 0.8089 ns 5,523,692.3
ExpandScale2 211.1 ns 0.6070 ns 0.5380 ns 4,737,221.7
ExpandScale3 182.7 ns 0.6277 ns 0.4900 ns 5,473,412.1
ExpandScale4 149.9 ns 0.6431 ns 0.6015 ns 6,669,759.0
ExpandScale5 171.0 ns 0.5085 ns 0.4756 ns 5,847,885.2

@StillLearnin

Copy link
Copy Markdown
Contributor Author

@roji I think it is ready for your review again. Thanks for your patience and input.

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks much better, @StillLearnin thanks for the great work and @YohDeadfall thanks for the valuable guidance.

@YohDeadfall feel free to merge, I'll add a note to the release notes.

@YohDeadfall
YohDeadfall merged commit 73705db into npgsql:dev May 15, 2018
@YohDeadfall YohDeadfall added this to the 4.0 milestone May 15, 2018
@roji

roji commented May 15, 2018

Copy link
Copy Markdown
Member

Thanks, added a line in the release notes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants