Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions cpp/src/arrow/buffer-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@ using std::string;

namespace arrow {

TEST(TestAllocate, Bitmap) {
std::shared_ptr<Buffer> new_buffer;
EXPECT_OK(AllocateBitmap(default_memory_pool(), 100, &new_buffer));
EXPECT_GE(new_buffer->size(), 13);
EXPECT_EQ(new_buffer->capacity() % 8, 0);
}

TEST(TestAllocate, EmptyBitmap) {
std::shared_ptr<Buffer> new_buffer;
EXPECT_OK(AllocateEmptyBitmap(default_memory_pool(), 100, &new_buffer));
EXPECT_EQ(new_buffer->size(), 13);
EXPECT_EQ(new_buffer->capacity() % 8, 0);
EXPECT_TRUE(std::all_of(new_buffer->data(), new_buffer->data() + new_buffer->capacity(),
[](int8_t byte) { return byte == 0; }));
}

TEST(TestBuffer, FromStdString) {
std::string val = "hello, world";

Expand Down
6 changes: 5 additions & 1 deletion cpp/src/arrow/buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,13 @@ Status AllocateResizableBuffer(const int64_t size,
return AllocateResizableBuffer(default_memory_pool(), size, out);
}

Status AllocateBitmap(MemoryPool* pool, int64_t length, std::shared_ptr<Buffer>* out) {
return AllocateBuffer(pool, BitUtil::BytesForBits(length), out);
}

Status AllocateEmptyBitmap(MemoryPool* pool, int64_t length,
std::shared_ptr<Buffer>* out) {
RETURN_NOT_OK(AllocateBuffer(pool, BitUtil::BytesForBits(length), out));
RETURN_NOT_OK(AllocateBitmap(pool, length, out));
memset((*out)->mutable_data(), 0, static_cast<size_t>((*out)->size()));
return Status::OK();
}
Expand Down
13 changes: 12 additions & 1 deletion cpp/src/arrow/buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -370,14 +370,25 @@ Status AllocateResizableBuffer(const int64_t size, std::shared_ptr<ResizableBuff
ARROW_EXPORT
Status AllocateResizableBuffer(const int64_t size, std::unique_ptr<ResizableBuffer>* out);

/// \brief Allocate a zero-initialized bitmap buffer from a memory pool
/// \brief Allocate a bitmap buffer from a memory pool
/// no guarantee on values is provided.
///
/// \param[in] pool memory pool to allocate memory from
/// \param[in] length size in bits of bitmap to allocate
/// \param[out] out the resulting buffer
///
/// \return Status message
ARROW_EXPORT
Status AllocateBitmap(MemoryPool* pool, int64_t length, std::shared_ptr<Buffer>* out);

/// \brief Allocate a zero-initialized bitmap buffer from a memory pool
///
/// \param[in] pool memory pool to allocate memory from
/// \param[in] length size in bits of bitmap to allocate
/// \param[out] out the resulting buffer (zero-initialized).
///
/// \return Status message
ARROW_EXPORT
Status AllocateEmptyBitmap(MemoryPool* pool, int64_t length,
std::shared_ptr<Buffer>* out);

Expand Down
15 changes: 14 additions & 1 deletion cpp/src/arrow/compute/kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,22 @@ struct ARROW_EXPORT Datum {
};

/// \class UnaryKernel
/// \brief An array-valued function of a single input argument
/// \brief An function of a single input argument.
///
/// Note to implementors: Try to avoid making kernels that allocate memory if
/// the output size is a deterministic function of the Input Datum's metadata.
/// Instead separate the logic of the kernel and allocations necessary into
/// two different kernels. Some reusable kernels that allocate buffers
/// and delegate computation to another kernel are available in util-internal.h.
class ARROW_EXPORT UnaryKernel : public OpKernel {
public:
/// \brief Executes the kernel.
///
/// \param[out] out The output of the function. Each implementation of this
/// function might assume different things about the existing contents of out
/// (e.g. which buffers are preallocated). In the future it is expected that
/// there will be a more generic mechansim for understanding the necessary
/// contracts.
virtual Status Call(FunctionContext* ctx, const Datum& input, Datum* out) = 0;
};

Expand Down
33 changes: 17 additions & 16 deletions cpp/src/arrow/compute/kernels/boolean.cc
Original file line number Diff line number Diff line change
Expand Up @@ -43,34 +43,35 @@ namespace compute {
class InvertKernel : public UnaryKernel {
Status Call(FunctionContext* ctx, const Datum& input, Datum* out) override {
DCHECK_EQ(Datum::ARRAY, input.kind());

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.

While this is not part of the PR, I think it's worth returning a Status::Invalid. In production this would likely trigger a segfault further down while invoking input.array().

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 fair, i tried to keep this style in the code I added. I would prefer to tackle this in one comprehensive cleanup if that is OK with you (https://issues.apache.org/jira/browse/ARROW-4264)

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.

👍

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.

In general I think we should type check as high in the call stack as possible. If this were being invoked inside a query engine I do not think it should be possible to pass the wrong kind of argument unless there is an error with the implementation. These kinds of "can't fail" errors (the result of Arrow developer error, not user input) should be caught with DCHECK

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.

I added a comment on the follow-up JIRA. I would lean slightly towards returning a bad-status but I could go either way, has this been discussed on the e-mail list? is it worth discussing?

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 really think we are putting the cart before the horse. These kernels will be invoked at a higher layer in general, and IMHO the type checking should occur there. I'm overwhelmed with other projects right now but I hope to shift my focus to the operator algebra (basically I plan to build a C++ version of https://github.com/ibis-project/ibis) before the end of quarter which will help resolve this uncertainty

constexpr int64_t kZeroDestOffset = 0;

const ArrayData& in_data = *input.array();
ArrayData* result;

out->value = ArrayData::Make(boolean(), in_data.length);
result = out->array().get();
std::shared_ptr<ArrayData> result = out->array();
result->type = boolean();

// Allocate or copy bitmap
// Handle validity bitmap
result->null_count = in_data.null_count;
std::shared_ptr<Buffer> validity_bitmap = in_data.buffers[0];
const std::shared_ptr<Buffer>& validity_bitmap = in_data.buffers[0];

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.

const Buffer& could even be more idiomatic

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.

In this case I need the reference to the shared_ptr because I copy it below (I suppose I could refactor slightly to avoid this). I changed the one below since it is not needed there.

if (in_data.offset != 0) {
RETURN_NOT_OK(CopyBitmap(ctx->memory_pool(), validity_bitmap->data(),
in_data.offset, in_data.length, &validity_bitmap));
DCHECK_LE(BitUtil::BytesForBits(in_data.length), validity_bitmap->size());
CopyBitmap(validity_bitmap->data(), in_data.offset, in_data.length,

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.

The validity bitmap may not be allocated at all if the null count is 0, so this will crash

result->buffers[0]->mutable_data(), kZeroDestOffset);
} else {
result->buffers[0] = validity_bitmap;
}
result->buffers.push_back(validity_bitmap);

// Allocate output data buffer
std::shared_ptr<Buffer> data_buffer;
RETURN_NOT_OK(InvertBitmap(ctx->memory_pool(), in_data.buffers[1]->data(),
in_data.offset, in_data.length, &data_buffer));
result->buffers.push_back(data_buffer);

// Handle output data buffer
const std::shared_ptr<Buffer>& data_buffer = in_data.buffers[1];
DCHECK_LE(BitUtil::BytesForBits(in_data.length), data_buffer->size());
InvertBitmap(data_buffer->data(), in_data.offset, in_data.length,
result->buffers[1]->mutable_data(), kZeroDestOffset);

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 code should probably not be executed if the length is 0. Technically it is not invalid for a buffer to be null if it is zero length. This suggests that the kernel should exit early if the length is 0 and avoid special casing here

return Status::OK();
}
};

Status Invert(FunctionContext* ctx, const Datum& value, Datum* out) {
InvertKernel kernel;
detail::PrimitiveAllocatingUnaryKernel kernel(
std::unique_ptr<UnaryKernel>(new InvertKernel()));

std::vector<Datum> result;
RETURN_NOT_OK(detail::InvokeUnaryArrayKernel(ctx, &kernel, value, &result));
Expand Down
43 changes: 43 additions & 0 deletions cpp/src/arrow/compute/kernels/util-internal.cc
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@
#include <algorithm>
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>

#include "arrow/array.h"
#include "arrow/status.h"
#include "arrow/table.h"
#include "arrow/util/logging.h"

#include "arrow/compute/context.h"
#include "arrow/compute/kernel.h"

namespace arrow {
Expand Down Expand Up @@ -162,6 +164,47 @@ Datum WrapDatumsLike(const Datum& value, const std::vector<Datum>& datums) {
}
}

PrimitiveAllocatingUnaryKernel::PrimitiveAllocatingUnaryKernel(
std::unique_ptr<UnaryKernel> delegate)
: delegate_(std::move(delegate)) {}

inline void ZeroLastByte(Buffer* buffer) {
*(buffer->mutable_data() + (buffer->size() - 1)) = 0;
}

Status PrimitiveAllocatingUnaryKernel::Call(FunctionContext* ctx, const Datum& input,
Datum* out) {
std::vector<std::shared_ptr<Buffer>> data_buffers;
const ArrayData& in_data = *input.array();
MemoryPool* pool = ctx->memory_pool();

// Handle the validity buffer.
if (in_data.offset == 0) {
// Validity bitmap will be zero copied
data_buffers.emplace_back();
} else {
std::shared_ptr<Buffer> buffer;
RETURN_NOT_OK(AllocateBitmap(pool, in_data.length, &buffer));
// Per spec all trailing bits should indicate nullness, since
// the last byte might only be partially set, we ensure the
// remaining bit is set.
ZeroLastByte(buffer.get());
buffer->ZeroPadding();
data_buffers.push_back(buffer);
}
// Allocate the boolean value buffer.
std::shared_ptr<Buffer> buffer;
RETURN_NOT_OK(AllocateBitmap(pool, in_data.length, &buffer));
// Some utility methods access the last byte before it might be
// initialized this makes valgrind/asan unhappy, so we proactively
// zero it.
ZeroLastByte(buffer.get());

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 learned recently that valgrind can detect bit-level access of uninitialized memory so that may be part of it

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.

In this case byte level was sufficient. I suppose I could have been more fine-grained with only zeroing out untouched bits but that doesn't seem worth it.

data_buffers.push_back(buffer);
out->value = ArrayData::Make(null(), in_data.length, data_buffers);

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.

There may be a better way to deal with assignment of output types, but we'll need more "Operator" infrastructure to be able to refactor

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.

By operator infrastructure, do you mean something like my initial attempts at the PR? Or some of the questions asked in ARROW-4333?

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 mean "operator infrastructure" similar to TensorFlow's operators https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/ops

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.

Operators compose with each other, on execution they dispatch to kernels


return delegate_->Call(ctx, input, out);
}

} // namespace detail
} // namespace compute
} // namespace arrow
23 changes: 23 additions & 0 deletions cpp/src/arrow/compute/kernels/util-internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ static inline void ZeroCopyData(const ArrayData& input, ArrayData* output) {

namespace detail {

/// \brief Invoke the kernel on value using the ctx and store results in outputs.
///
/// \param[out] outputs One ArrayData datum for each ArrayData available in value.
ARROW_EXPORT
Status InvokeUnaryArrayKernel(FunctionContext* ctx, UnaryKernel* kernel,
const Datum& value, std::vector<Datum>* outputs);
Expand All @@ -63,6 +66,26 @@ Datum WrapArraysLike(const Datum& value,
ARROW_EXPORT
Datum WrapDatumsLike(const Datum& value, const std::vector<Datum>& datums);

/// \brief Kernel used to preallocate outputs for primitive types.
class PrimitiveAllocatingUnaryKernel : public UnaryKernel {
public:
explicit PrimitiveAllocatingUnaryKernel(std::unique_ptr<UnaryKernel> delegate);
/// \brief Sets out to be of type ArrayData with the necessary
/// data buffers prepopulated.
///
/// This method does not populate types on arrays and sets type to null.
///
/// The current implementation only supports primitive boolean outputs and
/// assumes validity bitmaps that are not sliced will be zero copied (i.e.
/// no allocation happens for them).
///
/// TODO(ARROW-1896): Make this generic enough to support casts.
Status Call(FunctionContext* ctx, const Datum& input, Datum* out) override;

private:
std::unique_ptr<UnaryKernel> delegate_;
};

} // namespace detail

} // namespace compute
Expand Down
4 changes: 2 additions & 2 deletions cpp/src/arrow/util/bit-util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,8 @@ Status TransferBitmap(MemoryPool* pool, const uint8_t* data, int64_t offset,

TransferBitmap<invert_bits, false>(data, offset, length, 0, dest);

// As we have freshly allocated this bitmap, we should take care of zeroing the remaing
// bits.
// As we have freshly allocated this bitmap, we should take care of zeroing the
// remaining bits.
int64_t num_bytes = BitUtil::BytesForBits(length);
int64_t bits_to_zero = num_bytes * 8 - length;
for (int64_t i = length; i < length + bits_to_zero; ++i) {
Expand Down