Documentation
¶
Overview ¶
Package stretched is the repair for charge rows the stale-charge janitor stretched past their real end (#1619, #1630): it refreshed an open row's ended_at on a charger state that stuck after an unplug, so the row ran on through the vehicle's later drives. The repair caps ended_at at the last frame the vehicle read plugged in.
Like internal/repair/blips it FINDS its candidates by one predicate, and an apply must present the count and the sha256 of the sorted id list of an approved dry run; anything else aborts the transaction. It changes ended_at only, never later and never before started_at, in one transaction, after the old row (to_jsonb) went to charges_capped_backup and the durable CSV sink. It refuses open rows, rows written in the last hour and rows a user touched. A row whose plugged frames continue after a drive may hold a second, real charge; those are FLAGGED (reported, not changed): the rule is Flagger, and can be swapped.
Index ¶
- Constants
- Variables
- func Agree(integralKWh, socKWh float64) bool
- func Apply(ctx context.Context, d *sql.DB, batchID uuid.UUID, wantCount int, ...) (int, error)
- func DefaultFlagger(r Row) string
- func Restore(ctx context.Context, d *sql.DB, batchID uuid.UUID) (int, error)
- type Blocker
- type Flagger
- type Frame
- type Loc
- type NewRow
- type Options
- type Plan
- func (p Plan) ByVehicle() map[uuid.UUID]int
- func (p Plan) ClampTotals() (rows int, kwh float64)
- func (p Plan) CostDelta() (originals, newRows float64)
- func (p Plan) Digest() string
- func (p Plan) EmptyOriginals() int
- func (p Plan) FlaggedIDs() []uuid.UUID
- func (p Plan) HoursRemoved() float64
- func (p Plan) IDs() []uuid.UUID
- func (p Plan) IdleHoursInNewRows() float64
- func (p Plan) NewRowKinds() (l2, dc int)
- func (p Plan) NewRowTypes() (acHome, acAway, acOther, dc int)
- func (p Plan) PricedBySource() map[string]int
- func (p Plan) Repriceable() int
- func (p Plan) SoCModeTotals() (rows, disagree int)
- func (p Plan) SplitTotals() (rows, created int, kwh float64)
- func (p Plan) SplitsByVehicle() map[uuid.UUID]int
- type PriceFn
- type Queryer
- type Row
- type Segment
- type Split
- type Verdict
Constants ¶
const ( // MinStretch: a row is stretched when ended_at is this far past the last plugged frame. MinStretch = time.Hour // QuietFor: a row written more recently than this is left alone (the recorder or the janitor may still be on it). QuietFor = time.Hour )
Variables ¶
var ErrDrift = errors.New("stretched: the rows to cap differ from the approved dry run; nothing changed")
ErrDrift: the rows no longer match the approved dry run (nothing was changed).
var ErrOpenCharge = errors.New("stretched: a live charge was written in the last 15 minutes; run in a quiet hour")
ErrOpenCharge: a truck is charging now; the repair does not run.
var ErrRestoreBlocked = errors.New("stretched: the batch cannot be restored cleanly; nothing changed")
ErrRestoreBlocked: some group of the batch cannot be restored; nothing was changed.
Functions ¶
func Agree ¶
Agree reports whether the power integral and the SoC-derived energy are within 25% of each other (of the larger). Both must be positive.
func Apply ¶
func Apply(ctx context.Context, d *sql.DB, batchID uuid.UUID, wantCount int, wantDigest, reason string, allowOpen bool, opt Options, sink func([]phantom.BackupRow) error) (int, error)
Apply caps (and splits) in ONE transaction. It locks and re-selects the candidates, re-applies the rule at the current time, and aborts unless the count AND the digest equal the approved dry run's. The old rows (to_jsonb) go to sink (the durable CSV; an error aborts before anything is changed) and to charges_capped_backup. Each update asserts the cap is earlier than the old ended_at and not before started_at, and touches exactly one row; a split asserts the energy is conserved. New rows are plain inserts (no hooks, pushes or events fire) and are listed in the backup row so the undo deletes exactly them.
func DefaultFlagger ¶
DefaultFlagger flags a row with active charging frames after its first drive.
func Restore ¶
Restore undoes a batch from charges_capped_backup in ONE transaction, all or nothing: every original and created row is locked first; if any group is blocked (see lockRestore) the transaction rolls back with ErrRestoreBlocked and nothing changes, and any statement that does not behave (a delete or an update that touches an unexpected number of rows) rolls everything back too. Then the created rows are deleted (the original's old end overlaps them, charges_live_no_overlap) and the original's changed columns go back: ended_at, end_soc_pct, energy_added_kwh, cost, final_state and the power figures, and metadata with only the repair's own key removed, so keys added since survive. updated_at is touched by the table's trigger on every update, so it reads the restore time (the old value stays in the backup row). A batch with nothing left to restore is refused.
Types ¶
type Blocker ¶
Blocker is a reason a batch cannot be restored cleanly. Nothing is restored while any exists.
type Flagger ¶
Flagger decides whether a row may hold a second, real charge that the stretch swallowed, returning the reason ("" for no). The default looks at plugged frames after a drive; the rule is meant to be replaced by something that can also see a gradual SoC rise (DefaultFlagger is only the conservative start).
type Frame ¶
type Frame struct {
At time.Time
SpeedMph float64
PowerKW float64
SoC float64 // percent
Gear string
ChargingState string
}
Frame is one vehicle_state sample of the row, ascending by At.
type NewRow ¶
type NewRow struct {
ExternalID string
Start, End time.Time
SoCStart, SoCEnd float64
KWh float64
MaxPowerKW float64
AvgPowerKW float64 // kWh over the active hours
ActiveSeconds float64
FinalState string // the original's for the last segment, charging_complete for an earlier one
Lat, Lon float64
// Priced by Options.Price when it is set (zero values: left unpriced, "Not set").
Cost float64
PricePerKW float64
Currency string
CostSource string
Network string
Place string
}
NewRow is a charge the split creates from a parked segment after a drive.
type Options ¶
type Options struct {
// Flag replaces DefaultFlagger.
Flag Flagger
// Split turns rows with plugged frames after a drive into splits instead of flags.
Split bool
// CapBySoC (mode A) caps a row with no plugged frame and no charging after its first drive at the last pre-drive frame
// where the SoC rose (else at the first drive): a real charge on a vehicle that reports no charger status or power.
CapBySoC bool
// Price, when set, prices and places each new row of a split (see PriceFn). It runs in the plan, so the digest covers its
// result and the apply recomputes it: a changed rate or home location aborts the apply as drift.
Price PriceFn
}
Options select the optional behaviour of a plan.
type Plan ¶
type Plan struct {
Cap []Row
CapTo map[uuid.UUID]time.Time
BySoC map[uuid.UUID]bool // capped by the SoC rule (mode A)
SoCOff map[uuid.UUID]bool // mode A rows whose stored kWh disagrees with the pre-drive SoC gain
Splits map[uuid.UUID]*Split // the capped rows that also create new rows
Skipped map[string]int // reason -> count (flagged reasons included)
Flagged []Row
}
Plan is the classified candidates.
func (Plan) ClampTotals ¶ added in v0.41.3
ClampTotals counts the splits whose new rows were scaled down to the stored energy, and the kWh clamped away.
func (Plan) CostDelta ¶ added in v0.41.2
CostDelta is the change in cost the split makes: the originals' re-pricing by energy share (negative when they give energy away) and the cost of the new rows.
func (Plan) Digest ¶
Digest is the sha256 over the whole plan: for each capped row (sorted by id) its new ended_at and, for a split, the original's new end SoC, energy and cost and each new row's external id, start, end and kWh. A moved cap point, a different segment or a different energy figure changes it.
func (Plan) EmptyOriginals ¶ added in v0.41.2
EmptyOriginals counts the splits whose original holds no charge before the first drive.
func (Plan) FlaggedIDs ¶
FlaggedIDs returns the flagged ids, sorted.
func (Plan) HoursRemoved ¶
HoursRemoved is the total time the cap takes off the rows.
func (Plan) IdleHoursInNewRows ¶
IdleHoursInNewRows is the time the new rows span beyond their active charging (a segment that held a charge, a long idle and another charge becomes one row; its energy is right, its duration includes the idle).
func (Plan) NewRowKinds ¶
NewRowKinds counts the new rows by charge type, by peak power: DC fast (the recorder's DCFCMinKW) or L2/AC. The repair prices neither (the dry run reports it so the follow-up pricing step is sized).
func (Plan) NewRowTypes ¶ added in v0.41.2
NewRowTypes counts the new rows as AC at home, AC away from home, AC with no place (no saved home) and DC fast.
func (Plan) PricedBySource ¶ added in v0.41.2
PricedBySource counts the new rows by the cost source the pricing step gave them ("unpriced" for those it left alone: a fast charge, or AC away from home).
func (Plan) Repriceable ¶
Repriceable counts capped rows whose price came from the home rate or a network estimate: their cost may change with the window (time of use). The repair does not re-price; `rivolt reprice --ids` does, on the list the dry run writes.
func (Plan) SoCModeTotals ¶ added in v0.41.2
SoCModeTotals counts the rows capped by the SoC rule, and of those the ones whose stored kWh disagrees with the pre-drive SoC gain by more than 25% (capped all the same; their energy is not fixed by this repair).
func (Plan) SplitTotals ¶
SplitTotals is the number of rows split, the rows they create, and the energy re-attributed to the new rows.
type PriceFn ¶ added in v0.41.2
PriceFn fills Cost, PricePerKWh, Currency, CostSource, Network and Place on a charge built from a new row (it reads StartedAt, EndedAt, Lat, Lon, MaxPowerKW, ActiveSeconds and EnergyAddedKWh), for the user. It must not call Rivian, and must leave a row it cannot price as it is.
func NewPriceFn ¶ added in v0.41.2
NewPriceFn prices and places the new rows a split creates, with the recorder's own function (rivian.PriceUnbilled): an AC charge at home gets the user's home rate (cost_source home_rate) and a place, an AC charge away from home is placed "away" and left unpriced. A DC fast charge is left unpriced and unplaced here: it needs the chargers archive and network detection, which `rivolt reprice --detect` has, with its own dry run. No call reaches Rivian: the lookups are settings reads.
type Queryer ¶
type Queryer interface {
QueryContext(ctx context.Context, q string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, q string, args ...any) *sql.Row
}
Queryer is *sql.DB or *sql.Tx.
type Row ¶
type Row struct {
ID uuid.UUID
UserID uuid.UUID
VehicleID uuid.UUID
StartedAt time.Time
EndedAt time.Time
UpdatedAt time.Time
FinalState string
Source string
CostSource string
// FirstDrive is the start of the first drive inside the row.
FirstDrive time.Time
// LastPlugged is the last frame before the first drive where the vehicle read plugged in and stood still (zero: none).
LastPlugged time.Time
// PluggedAfterDrive: an active charging frame (power, standing still) exists after FirstDrive.
PluggedAfterDrive bool
// What a person or another table says about the row.
HasRestamp bool
HasReceipt bool
Edited bool
// The split's evidence (loaded for rows with plugged frames after a drive).
RivianVehicleID string
PackKWh float64
EnergyKWh float64
StartSoC, EndSoC float64
PricePerKWh float64
Cost float64 // the stored cost (0: none)
LastPluggedBeforeDrive time.Time
Frames []Frame
Locs []Loc
// Taken is the set of external ids already used by the vehicle's charges (a new row must not collide).
Taken map[string]bool
}
Row is a candidate: a live charge with at least one same-vehicle drive starting inside it, and the evidence.
func Select ¶
Select loads every live charge with a same-vehicle drive starting strictly inside it, with the evidence. With forUpdate the charge rows are locked, for the apply transaction. With frames the rows that have plugged frames after a drive also carry their vehicle_state frames and the vehicle's taken external ids, for the split.
type Segment ¶
type Segment struct {
Start, End time.Time // first and last parked frame of the stretch
FirstActive time.Time // first charging_active frame with power > 0
SoCStart float64
SoCEnd float64
IntegralKWh float64 // trapezoidal power x time over consecutive active frames
}
Segment is a parked stretch that holds a charge.
func DetectSegments ¶
DetectSegments returns the parked segments after firstDrive that gained at least 5 SoC points and have charging_active frames at power > 0. A drive (gear D/R/N, or speed over 2 mph) ends a segment, so one row can yield several. Frames before firstDrive are ignored.
type Split ¶
type Split struct {
OrigEndSoC float64
OrigKWh float64
OrigCost *float64 // set when the original is auto-priced and re-priced by energy share
// The original's figures recomputed from the frames inside its own window: the stored ones may belong to an
// absorbed (DC) session.
OrigMaxKW, OrigAvgKW, OrigActiveSec float64
// charging_complete when the SoC rose over the original's window, else abandoned.
OrigFinalState string
// EmptyOriginal: nothing in the original's span before the first drive was a charge (no plugged frame, no SoC gain). It
// is kept as a zero-energy abandoned row ended at the first drive; its remainder is still stored minus the new rows.
EmptyOriginal bool
// ClampedKWh is the excess the new rows were scaled down by (0: not clamped).
ClampedKWh float64
News []NewRow
}
Split is the plan for a row that holds absorbed charges: the original keeps what was before the first drive (energy conserved: stored minus the new rows), and each parked segment after a drive becomes a row.
type Verdict ¶
type Verdict struct {
CapTo time.Time // set when the row is capped
BySoC bool // capped by the SoC rule (mode A), not by a plugged frame
SoCOff bool // with BySoC: the stored kWh disagrees with the pre-drive SoC gain
Split *Split // set when the row is split (CapTo is the original's new end)
Reason string // why a row is skipped or flagged ("" when capped)
Flag bool // skipped because it may hold an absorbed charge
}
Verdict is the rule's answer for one row.