Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Add RFC for improving Vrl performance #9812

Closed
wants to merge 7 commits into from
Closed
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
260 changes: 260 additions & 0 deletions rfcs/2021-10-14-9811-vrl-performance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
# RFC 9811 - 2021-10-14 - VRL performance

VRL is currently a perfornce bottleneck in Vector. There are a number of
StephenWakely marked this conversation as resolved.
Show resolved Hide resolved
potential avenues for us to explore in order to optimise VRL.
StephenWakely marked this conversation as resolved.
Show resolved Hide resolved

## Context

https://github.com/vectordotdev/vector/issues/6680
JeanMertz marked this conversation as resolved.
Show resolved Hide resolved

https://github.com/vectordotdev/vector/issues/6770

## Scope

### In scope

This RFC discussing a number of changes that can be made to the Vrl runtime to
StephenWakely marked this conversation as resolved.
Show resolved Hide resolved
enable it to process data faster.

### Out of scope

Out of scope are:

- improvements to the build time of VRL (mainly caused by lalrpop).
- changes to improve the functionality of VRL.
- Using a bytecode VM to execute VRL (this will come in a followup PR).

## Pain

### Allocations

A lot of performance is taken up by excessive allocations. It is likely that
reducing the number of allocations will produce the biggest performance gain
for VRL and thus this should be the main area of focus.

Where we have clones that we should try to avoid:

- At the start of the Remap transform. The entire event is cloned so we can
StephenWakely marked this conversation as resolved.
Show resolved Hide resolved
roll back to it on error.
- In the interface between VRL and Vector. The object is cloned on both `get`
and `set` operations.
StephenWakely marked this conversation as resolved.
Show resolved Hide resolved

Let's have a look at the life of the event `{ "foo": { "bar": 42 } }` in this
simple VRL source:

```coffee
.zub = .foo
```

1. The whole event is cloned in order to create a backup in case the event is
aborted. [here](https://github.com/vectordotdev/vector/blob/v0.17.0/src/transforms/remap.rs#L135)
StephenWakely marked this conversation as resolved.
Show resolved Hide resolved
2. Then we need to access `.foo`. The `.foo` field needs to be pulled out of
the event and converted to a `vrl::Value`. [here](https://github.com/vectordotdev/vector/blob/v0.17.0/lib/vector-core/src/event/vrl_target.rs#L130)
This actually involves two allocations.
Comment on lines +51 to +53
Copy link
Contributor

Choose a reason for hiding this comment

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

As a tangent, I wonder if we should investigate changing this part of the runtime to take ownership of the Event, instead of taking a mutable reference.

It seems to me that since the transform gets ownership of the event, we should pass that ownership on to the runtime so that it can optimize value access by taking actual values out of the hashmap, instead of cloning them.

This would avoid the initial clone (we still need reference counting for when more than one expression needs access to the value).

a. First the value is cloned.
b. Next it is converted into a `vrl::Value`.
[here](https://github.com/vectordotdev/vector/blob/v0.17.0/lib/vector-core/src/event/value.rs#L308)
Since `.foo` in at Object, this involves allocating a new `BTreeMap` then
looping over each field, allocating a new `vrl::Value` for each one.
3. We then assign it to `.zub`. To do this the value is cloned and inserted
into our event. [here](https://github.com/vectordotdev/vector/blob/v0.17.0/lib/vrl/compiler/src/expression/assignment.rs#L369)

Each time an object is passed between Vector and VRL an allocation is made.

### Boxing

VRL works by compiling the source to a tree based AST (abstract syntax tree).
To execute the program the tree is walked, each node is evaluated with the
current state of the program. Each node is not necessarily stored in memory
close to the next node. As a result it does not fully utilise the cpu cache.

Also, each node in the AST is boxed which causes extra pointer indirection.


## Proposal

### Implementation

### Reducing allocations

#### Use reference counting

One of the data types that is cloned the most is `vrl::Value`. A lot of these
clones are because VRL needs to maintain multiple references to a single value.
In the Rust model, this can get highly awkward handling the lifetimes.

If VRL used reference counting instead, the allocations can be avoided. Each
clone would just increase a count into the underlying data store which is
significantly cheaper. When the value goes out of scope the count is reduced.
If the count reaches 0, the memory is freed.

VRL needs to wrap the data in an `Rc`. This does mean pulling the data out of
Copy link
Contributor

Choose a reason for hiding this comment

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

Why an Rc and not a Cow?

Copy link
Member

Choose a reason for hiding this comment

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

I believe this is because it needs to be owned in multiple places, and Cow is more accurately "copy-on-own" (which can then "write" to the owned copy). See for example assignment:

Single { target, expr } => {
let value = expr.resolve(ctx)?;
target.insert(value.clone(), ctx);
value
}

That value needs to be retained in the source, inserted into the target, and returned, requiring a clone (or even two, with one implicit in expr.resolve).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

What would the advantages of a Cow be? I can think mutation would be safer since it copies rather than panics. Anything else?

@bruceg is on the mark, ownership gets complicated. Ultimately the event store should own all the data, but the data is not always created there, it is often created in an expression and then added to the event store - sometimes whilst also passing it somewhere else.

Copy link
Contributor

Choose a reason for hiding this comment

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

Looks like there's no advantages but this might be worthwhile spelling out in an alternatives section.

Copy link
Member

Choose a reason for hiding this comment

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

Well, the advantage of a Cow would be to avoid the heap allocation and reference count machinations, reducing indirection and increasing performance, since the only time it would get cloned is when it actually has to. The only way I could see to make this work is to pass in the return buffer as a mut parameter somehow instead of returning it, but I have no idea what other issues that would raise.

the original event, which is not wrapped in `Rc`. Currently the data is cloned
at the start of the transform. Since this replaces the need for that clone the
additional cost required will be minimal - just an additional allocation
required for each part of the value to cater for the reference count.

Each field in the event can be pulled out lazily as it is used.

At the end of the process any modified data can be reapplied to the event. This
should be possible with a simple `mem::swap`. If the process is aborted, we
don't do anything since the original event is still unmodified.

Currently, the only point at which data is mutated is when updating the event.
With this change mutation would occur when updating the VRL data store.

Some changes will need to be made:

1. Change `vrl::Value::Object` to wrap the Value in `Rc<RefCell<>>`:
`Object(BTreeMap<String, Rc<RefCell<Value>>>)`
2. Change `vrl::Value::Array` to wrap the Value in `Rc<RefCell<>>`:
`Array(Vec<Rc<RefCell<Value>>>)`
3. Change the methods of the `Target` trait to use `Rc<RefCell<>>`:

```rust
fn insert(&mut self, path: &LookupBuf, value: Rc<RefCell<Value>>) -> Result<(), String>;
fn get(&self, path: &LookupBuf) -> Result<Option<Rc<RefCell<Value>>>, String>;
fn remove(
&mut self,
path: &LookupBuf,
compact: bool,
) -> Result<Option<Rc<RefCell<Value>>>, String>;
```

4. Change `VrlTarget`, to store the event as a `<Rc<RefCell<vrl_core::Value>>`
rather than a `Value`. This does mean that when the remap transform runs
all the data from `Value` will need converting to `vrl_core::Value`. There
is a cost involved here. However it does mean that we can avoid the initial
clone that is often necessary, which should soak up most of the extra
expense.
5. Update everything to use `Rc<RefCell<Value>>`. There is a risk here since
using `RefCell` moves the borrow checking to the runtime rather than compile
time. Affected areas of code will need to be very vigorously tested to avoid
runtime panics. Fortunately a lot of Vrl relies on creating new values
rather than mutating existing, so there isn't too much code that will be
affected.
Comment on lines +130 to +135
Copy link
Member

Choose a reason for hiding this comment

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

The fact that we do very little actual mutation of individual values seems very important. Would it be feasible to eliminate it (and the RefCell) entirely? The fact that we're currently cloning those values implies that we're already not sharing mutations, unless I'm misunderstanding something.

A related idea (maybe off the mark, but wanted to mention) would be to keep the actual values in our "working set" in a single place (maybe just a HashMap, maybe something fancier like a slotmap) and pass around Copy indexes/keys into that structure. Then we can lazily read through to the actual event to fill it, replace values wholesale during execution (as opposed to mutation), and apply changes to the actual event at the end (similar to what you mentioned elsewhere).

6. `Value` is no longer `Send + Sync`. There are some nodes in the AST that
Copy link
Contributor

Choose a reason for hiding this comment

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

FWIW I like dropping Send + Sync from remap. It pins it as single-threaded -- good -- and allows us to do extra tricks at the topology level.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The ultimate reason Vrl needs Send + Sync is because it needs to store the Program in the transform and the FunctionTransform trait needs Send + Sync. Is there a way around that?

Copy link
Contributor

Choose a reason for hiding this comment

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

Ah, sorry, I meant to say I was pro the removal of Send + Sync from Value and not remap generally.

need to store a `Value`, for example `Variable` stores a `Value`. We need
to identify if this `Value` is actually necessary (it's not clear to me).
If it isn't we can remove it.
If it is we need to create a thread safe variable of `Value` that can be
stored here and then converted into a `Value` at runtime.

Initial experiments roughly showed a reduction from 1m20s to 1m02s to push
100,000 records through Vector using reference counting.
StephenWakely marked this conversation as resolved.
Show resolved Hide resolved

### Flow analysis

One of the expensive operations is path lookup.

There may be certain situations where this can be improved by analyising the
flow of data at compile time.

For example, with this code:

```coffee
.thing[3].thang = 3
log(.thing[3].thang)
```

the compiler can work out that the variable written to and read from is the
same and can thus store that data in an array, any access can be made via a
quick O(1) lookup using the index to the array.

The flow analysis can become fairly complex.

```coffee
.message = parse_json!(.message)
.message[3] = parse_json!(.message[2])
log(.message[3].thing)
```

Functions like `parse_json` would need access to this array and hints as to
what paths should be stored.

A lot more thought needs to go into this before we can consider implementing
it.
StephenWakely marked this conversation as resolved.
Show resolved Hide resolved

#### Use a Bump Allocator?

We could use a library such as [bumpalo](https://crates.io/crates/bumpalo).

A bump allocator will allocate memory up front. This memory will then be used
during the runtime. At the end of each transform the bump pointer is reset to
the start - effectively deallocating all the memory used during the transform
with very little cost.

The downside to a bump allocator is we need to make sure sufficient memory is
allocated up front.
StephenWakely marked this conversation as resolved.
Show resolved Hide resolved

This is probably not ready yet until this PR for `BTreeMap` lands.
https://github.com/rust-lang/rust/pull/77438

### Optimizing stdlib functions

There is a small number of functions in the stdlib that follow a pattern of
converting `Bytes` into a `Cow<str>` using `String::from_utf8_lossy`. The
string is then allocated using `.into_owned()`.

With some shifting around it should be possible to avoid this extra allocation,
possibly at the cost of a slight reduction in code ergonomics.

The functions that could possibly be optimised are:

`contains`
`ends_with`
`starts_with`
`join`
`truncate`

## Rationale

Vrl is often identified as a bottleneck in performance tests. Being a key
component in Vector any optimisation that can be done in Vrl will benefit
Vector as a whole.

## Drawbacks

Downsides to moving Vrl to use reference counting:

- Using `RefCell` does move the borrow checking to the runtime. Without compile
time checks the chances of a panic are much higher.
Comment on lines +220 to +221
Copy link
Contributor

@JeanMertz JeanMertz Nov 2, 2021

Choose a reason for hiding this comment

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

It would be good to give some examples on what we should watch out for.

I would probably favour having a wrapper type that only exposes try_borrow, and having the error implement ExpressionError, so that we avoid panicking Vector in production.

Thinking about this, given that VRL functions return new values instead of mutated ones, do we have a list of places we'd need to borrow_mut? If those are minimally required, we could keep that API internal to the compiler, to avoid exposing it to functions and thus significantly reducing the risk of errors.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

There are not many places where we do need to borrow_mut - mostly in the Target implementation. I think any panics would be indicative of a bug, so I think we should probably fail hard and make sure the bugs aren't there by testing rigorously.


## Alternatives


### References

This RFC proposes using Reference Counted Values. However it is possible that
we can use pure references. This would save the overhead of having to maintain
a reference count using `Rc`. The data would be owned by the `Target`. The
signature for `get` would become:

```rust
fn get(&'a self, path: &LookupBuf) -> Result<Option<&'a Value>, String>;
```

In theory, this change would be more performant than reference counting. However,
the extra lifetimes could cause sufficient problems as to make this solution
unworkable. We need to work on a spike to see what issues may arise from this
approach before determining the way forward.

## Outstanding Questions

## Plan Of Attack

Incremental steps to execute this change. These will be converted to issues
after the RFC is approved:

- [ ] Submit a PR with spike-level code _roughly_ demonstrating the change for
referencing counting. See [here](https://github.com/vectordotdev/vector/pull/9785).
- [ ] Submit a PR with spike-level code _roughly_ demonstrating the change for
references.
- [ ] Optimise the relevant stdlib functions.


## Future Improvements

Compiler technology can be a very advanced area. A lot of research has gone
into the area which can be leveraged in improving Vrl. As we look more into the
topic more and more ideas for areas of improvement will surface.