near / nearcore

Reference client for NEAR Protocol
https://near.org
GNU General Public License v3.0
2.3k stars 601 forks source link

Investigate different representations for the gas book-keeping #5295

Open nagisa opened 2 years ago

nagisa commented 2 years ago

Right now maintaining the gas counters involves a structure with 3 distinct fields as seen here. This specific format necessitates an operation such as (pseudocode)

let used_gas = (instruction_count_in_bb as u32 as u64).wrapping_mul(structure.cost_per_instruction)
    .overflowing_add(structure.used_gas)?;
structure.used_gas = used_gas;
if used_gas > structure.max_gas {
    return Err(GasExhausted);
}

at the beginning of every basic block. Given the frequency at which this code is called, this is still going to be comparatively expensive, especially due to the number of branches in the gas check. Replacing the structure with something like remaining_instructions: u64 and utilizing the following implementation

sub $instruction_count_in_bb,%(remaining_instructions)
jc .gas_exhausted

is likely the most efficient way to implement the tracking of gas in the hot code area. To enable this we would need to:

  1. Carefully convert the gas to the number of instructions and back as necessary (making sure to handle the residuals correctly) across the places in nearcore where we deal with gas counts;
  2. Ensure that we re-codegen contracts (and evict from cache the old machine code) when the instruction costs change;

As a more straightforward option, we could continue operating in gas everywhere, but rather than counting the consumed gas and checking against the limit we could adjust the instrumentation to decrement from a counter that represents the remaining gas.

stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity in the last 2 months. It will be closed in 7 days if no further activity occurs. Thank you for your contributions.

stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity in the last 2 months. It will be closed in 7 days if no further activity occurs. Thank you for your contributions.

jakmeier commented 1 year ago

Is this still relevant? @nagisa

nagisa commented 1 year ago

Yes.