Skip to content

Added support for nullable scalars - #1773

Closed
YohDeadfall wants to merge 14 commits into
npgsql:devfrom
YohDeadfall:NullableScalars
Closed

YohDeadfall wants to merge 14 commits into
npgsql:devfrom
YohDeadfall:NullableScalars

Conversation

@YohDeadfall

Copy link
Copy Markdown
Contributor

I've moved calls of NpgsqlTypeHandler.Read<T> from the GetFieldValue<T> implementations into delegates to handle all values in the existing try-catch blocks without additional type checks. An delegate cache is implemented via the NullableHandler class with is singleton, but I've found that GetFieldValue<T> is used internally when opening a connection and NullableHandler gets instantiated even if the GetFieldValue<T> method isn't used in user code. Therefore I think that the class should be removed and all its fields should be moved into NpgsqlDataReader to eliminate additional JIT instructions.

Fixes #1728

@roji

roji commented Jan 14, 2018

Copy link
Copy Markdown
Member

Thanks for submitting this, it's good to see contributions to Npgsql. Here are some general remarks.

First, one of the main focuses of 3.3 is performance - I'm really working on optimizing things and make Npgsql into a "high-performance" database driver. Your solution an additional (concurrent) dictionary lookup when reading all reference values such as strings (the delegate lookup in NullableHandler.TryGet()). In addition, reading for all values (nullable or otherwise) is now done via an additional delegate layer, which is bound to have some impact on performance.

In general, I'd want a PR like this to also include benchmark results to understand the impact on reading regular values (both non-nullables such as int and reference types such as string). I'm not 100% it's possible to add this feature without some impact (this depends on how aggressively the JIT can optimize away some checks in generic method code), but at the very least this impact should be minimal.

I have quite a few other more specific remarks, but I'd rather we have those conversations over a PR whose general approach is more performance-oriented as it would probably look quite different. I'm going to leave this open for further discussion for now but feel free to close and open a 2nd PR.

(Regardless of the above, I agree with you that there's little value in a separate NullHandler class and that its code can be refactored into NpgsqlDataReader.)

@roji

roji commented Jan 14, 2018

Copy link
Copy Markdown
Member

Just as a general comment: in some cases I avoid a performance hit on the normal cases simply by executing the rarer/more exotic case only in case of a "failure" in the normal path. In other words, you can introduce the nullable handling code only after an attempt to handle the reading via the normal path fails, i.e. since the type handler does not implement INpgsqlTypeHandler<int?> (see NpgsqlTypeHandler<T>.Read<TAny>()). This would make sure we'd only hit expensive nullable-handling code (which uses delegates etc.) in the cases where we absolutely need to.

@YohDeadfall

Copy link
Copy Markdown
Contributor Author

Yep, agree. I think about two things which could improve performance:

  1. Add an additional check if T is string. Therefore the cache lookup would not be performed.
  2. Cache the read and readAsync delegates in the current field descriptor. It would improve performance in the case of reading multiple rows.

I will try our ideas and write the benchmark to test them. Results will be posted here later so they could be compared.

@roji

roji commented Jan 14, 2018

Copy link
Copy Markdown
Member

I don't think it's enough just to check if T is string - there are other reference types out there as well. I'd prefer a "fallback approach" as I wrote above:

  1. Keep the current code which attempts to read the value as T
  2. For int? this will fail, since the int type handler doesn't implement INpgsqlTypeHandler<int?>.
  3. Instead of immediately throwing an InvalidCastException as the code currently does, check if T happens to be nullable and only then branch to the special logic.

@YohDeadfall

Copy link
Copy Markdown
Contributor Author

Environment

BenchmarkDotNet=v0.10.10, OS=Windows 10.0.17063
Processor=Intel Xeon CPU E5-2687W 0 3.10GHzIntel Xeon CPU E5-2687W 0 3.10GHz, ProcessorCount=32
  [Host]     : .NET Framework 4.6.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3036.0
  DefaultJob : .NET Framework 4.6.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3036.0

Note. Executed on the virtual machine with Hyper-V hypervisor. Host OS is Windows Server 2012 without other virtual machines.

Basic results (without nullable support)

Method Mean Error StdDev Op/s
NullableField NA NA NA NA
ValueTypeField 205.1 ns 5.400 ns 14.32 ns 4,874,897.7
ReferenceTypeField 461.4 ns 9.185 ns 21.29 ns 2,167,293.3
ObjectField 427.0 ns 10.123 ns 26.13 ns 2,341,904.0

Results with nullable support

Method Mean Error StdDev Op/s
NullableField 239.9 ns 6.490 ns 17.766 ns 4,167,541.9
ValueTypeField 216.0 ns 4.421 ns 9.325 ns 4,630,347.0
ReferenceTypeField 394.8 ns 38.268 ns 112.836 ns 2,533,180.1
ObjectField 435.3 ns 8.596 ns 14.827 ns 2,297,133.0

Results with nullable support (when T handled via delegates, when not object)

internal static class Handler<T>
{
    public static readonly ReadDelegate<T> Read;
    public static readonly ReadAsyncDelegate<T> ReadAsync;
    public static bool ThrowOnNull = NullableHandler.Construct(out Read, out ReadAsync);
}

static class Handler
{
    static readonly MethodInfo _readNullableMethod = new ReadDelegate<int?>(ReadNullable<int>).GetMethodInfo().GetGenericMethodDefinition();
    static readonly MethodInfo _readNullableAsyncMethod = new ReadAsyncDelegate<int?>(ReadNullable<int>).GetMethodInfo().GetGenericMethodDefinition();

    static T? ReadNullable<T>(NpgsqlReadBuffer buffer, int columnLen, FieldDescription fieldDescription) where T : struct
        => fieldDescription.Handler.Read<T>(buffer, columnLen, fieldDescription);

    static async ValueTask<T?> ReadNullable<T>(NpgsqlReadBuffer buffer, int columnLen, bool async, FieldDescription fieldDescription) where T : struct
        => await fieldDescription.Handler.Read<T>(buffer, columnLen, async, fieldDescription);

    static T ReadCommon<T>(NpgsqlReadBuffer buffer, int columnLen, FieldDescription fieldDescription)
        => fieldDescription.Handler.Read<T>(buffer, columnLen, fieldDescription);

    static ValueTask<T> ReadCommon<T>(NpgsqlReadBuffer buffer, int columnLen, bool async, FieldDescription fieldDescription)
        => fieldDescription.Handler.Read<T>(buffer, columnLen, async, fieldDescription);

    public static bool Construct<T>(out ReadDelegate<T> read, out ReadAsyncDelegate<T> readAsync)
    {
        var underlyingType = Nullable.GetUnderlyingType(typeof(T));
        if (underlyingType != null)
        {
            read = (ReadDelegate<T>)_readNullableMethod.MakeGenericMethod(underlyingType).CreateDelegate(typeof(ReadDelegate<T>));
            readAsync = (ReadAsyncDelegate<T>)_readNullableAsyncMethod.MakeGenericMethod(underlyingType).CreateDelegate(typeof(ReadAsyncDelegate<T>));
            return false;
        }
        else
        {
            read = ReadCommon<T>;
            readAsync = ReadCommon<T>;
            return true;
        }
    }
}
public override T GetFieldValue<T>(int column)
{
    CheckRowAndOrdinal(column);

    SeekToColumn(column);
    if (ColumnLen == -1)
    {
        if (Handler<T>.ThrowOnNull)
            throw new InvalidCastException("Column is null");
        else
            return default;
    }

    var fieldDescription = RowDescription[column];
    try
    {
        return typeof(T) == typeof(object)
            ? (T)fieldDescription.Handler.ReadAsObject(Buffer, ColumnLen, fieldDescription)
            : Handler<T>.Read(Buffer, ColumnLen, fieldDescription);
    }
    catch (NpgsqlSafeReadException e)
    {
        throw e.InnerException;
    }
    catch
    {
        Connector.Break();
        throw;
    }
}
Method Mean Error StdDev Op/s
NullableField 209.0 ns 4.337 ns 11.195 ns 4,785,463.5
ValueTypeField 211.3 ns 4.233 ns 4.157 ns 4,731,545.9
ReferenceTypeField 434.5 ns 8.610 ns 15.079 ns 2,301,528.1
ObjectField 421.1 ns 8.440 ns 20.222 ns 2,374,629.2

@YohDeadfall

Copy link
Copy Markdown
Contributor Author

It makes sense to use delegates to handle all T except object to not to produce an additional state machine. What do you think, @roji?

@roji

roji commented Jan 22, 2018

Copy link
Copy Markdown
Member

I'll try to find some time to review and comment ASAP.

@YohDeadfall

Copy link
Copy Markdown
Contributor Author

Rebased and waiting for your comments.

@roji

roji commented Jan 30, 2018

Copy link
Copy Markdown
Member

@YohDeadfall thanks, I promise to try and review in the next few days... a lot of things on my plate.

@roji
roji force-pushed the dev branch 3 times, most recently from 5151389 to 8d35b8a Compare February 24, 2018 06:40
@roji
roji force-pushed the dev branch 2 times, most recently from 349e870 to 0fcf927 Compare March 7, 2018 16:26
@YohDeadfall

Copy link
Copy Markdown
Contributor Author

@roji Review please.

@roji

roji commented Mar 10, 2018

Copy link
Copy Markdown
Member

Am slowly getting to it...

@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.

Finally got around to this. This looks much better than before and is pretty much ready. Take a look at my suggestions and let me know what you think.

I'll try to react ASAP to your comments/changes so we can finally merge this soon.

Comment thread src/Npgsql/NpgsqlDataReader.cs Outdated
{
public static readonly ReadDelegate<T> Read;
public static readonly ReadAsyncDelegate<T> ReadAsync;
public static bool Exists = NullableHandler.Construct(out Read, out ReadAsync);

@roji roji Mar 11, 2018 •

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.

Just to make this a bit more readable, why not do the construction part in a static constructor on this class. which would set everything?

Another thought is to check whether the JIT knows to elide the check if (Nullable.GetUnderlyingType(typeof(T)) in general methods. If it is (not likely), it makes sense to move the checks to the call sites rather than checking on Exists, since they will be elided. Either way it doesn't block this PR (especially because of the proposal below to move the check from the readers to Read<TAny>).

I'm saying this because I know that the JIT knows to elide if (typeof(T) == typeof(string)), which allows for all sort of generics "specialization" with 0 runtime cost. For example, this should be happening in GetFieldValue<T>() when checking typeof(T) == typeof(object).

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.

Unfortunately, not. The JIT doesn't elide such things, but there is an issue (dotnet/coreclr#2591) in the CoreCLR repo.

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.

The non-generic NullableHandler class is a factory which holds everything it needs and exposes only the Construct<T> method, nothing more. If I move the construction part to the static constructor of NullableHandler<T> which is a holder, then I must change access modifiers of all factory members to internal or public to make them accessible from the generic class. Also it would mix purposes of these classes. So I did what I did. It's a common practice to split logic (see Nullable and Nullable<T> for example).

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.

Added lost readonly. It would improve performance because the JIT treats readonly fields as constants.

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.

My proposal was simpler I think... All I was thinking was to move the invocation of Construct<T> to a static constructor on the same class, not to change the relationship NullableHandler and NullableHandler<T>. It's just a minor readability suggestion (when I first looked at your code, I actually misread the assignment to Exists as a property getter...).

So instead of:

internal static class NullableHandler<T>
{
    public static readonly ReadDelegate<T> Read;
    public static readonly ReadAsyncDelegate<T> ReadAsync;
    public static readonly bool Exists = NullableHandler.Construct(out Read, out ReadAsync);
}

it would be:

internal static class NullableHandler<T>
{
    static NullableHandler() {
        Exists = NullableHandler.Construct(out Read, out ReadAsync);
    }
    public static readonly ReadDelegate<T> Read;
    public static readonly ReadAsyncDelegate<T> ReadAsync;
    public static readonly bool Exists;
}

(or something similar).

If you don't like this for any reason we can skip it.

This is my last comment, after this I can merge, let me know.

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.

Ah so (: It's not a problem. Will change.

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.

Done. Let's merge.


internal delegate ValueTask<T> ReadAsyncDelegate<T>(NpgsqlReadBuffer buffer, int columnLen, bool async, FieldDescription fieldDescription);

internal static class NullableHandler<T>

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 approach is great, especially compared to the previous ConcurrentDictionary approach.

var fieldDescription = RowDescription[column];
try
{
if (NullableHandler<T>.Exists)

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.

I'd still like to see this check happen only after a failure to read the value normally. Why not move this to https://github.com/npgsql/npgsql/blob/dev/src/Npgsql/TypeHandling/NpgsqlSimpleTypeHandler.cs#L122 (for simple) and to https://github.com/npgsql/npgsql/blob/dev/src/Npgsql/TypeHandling/NpgsqlTypeHandler%60.cs#L98 (for non-simple)? This would completely remove the nullable handling from the regular handling flow.

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 want to handle nulls in the catch block?

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.

No; definitely not (we shouldn't do normal flow via exception handling). But the ReadAny<TAny> methods on Npgsql{Simple,}TypeHandler are the place where we try to cast the handler to the interface which handles the user-requested type. If that cast fails, that's a good place for falling back and checking whether maybe the type is nullable etc. I'm still not sure if it's going to work well, but let's give it a shot.

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.

Does it make sense? If len equals to -1 then there is no reason to use a type handler. There are no data in the buffer to read.

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.

Let me try to explain: I only meant that these two lines of nullable-handling might be better in Read<Any>, the case where ColumnLen == -1 should probably stay exactly where it is... If it's not clear I can write some code.

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.

Understand you. You have said that plan to merge NpgsqlDefaultDataReader and NpgsqlSequentialDataReader. Therefore, it would be better to keep the code in the current places because after the merge the only one file will exist where NullableHandler<T> will be used. I want to say that it would be better to keep the class in a single file and use it only in 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.

OK, let's keep it as it is for now - we can always refactor it later.

Comment thread test/Npgsql.Benchmarks/GetFieldValue.cs Outdated
}

[Benchmark]
public void NullableField()

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.

Expression-bodied methods (here and below)


namespace Npgsql.Tests.Types
{
public class NullableTypeTests : TestBase

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.

We can move this to ReaderTests, which is already parameterized on sequential and non-sequential (i.e. this test will automatically be executed twice).

@roji

roji commented Mar 14, 2018

Copy link
Copy Markdown
Member

Sqashed, rebased and merged via 85a6f51.

Thanks @YohDeadfall!

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.

2 participants