Gaps

Gap ranges, their classification and whether they can be filled.

GapRange

GapRange is one hole: a time range, a status and a reason. It is the element type of ListGapsResponse.Gaps, and it carries Fillable.

type GapRange struct {
	StartTs int64
	EndTs   int64
	Status  GapStatus
	Reason  GapReason
}

GapRange represents a time range with missing or invalid data.

func CoalesceGapPoints(points []CandlePoint, interval int64) []GapRange

CoalesceGapPoints turns a query result’s per-interval gap markers into the RANGES they actually describe.

Why this has to exist

A candle query answers per interval: every slot with no data comes back as its own CandlePoint with IsGap set. That is the right granularity for a caller walking the series, and the wrong one for a caller asking WHERE the holes are. A twelve-minute outage on a 1m stream arrives as twelve markers, a weekend as 2,880, and none of them carries an extent – so a consumer can plot twelve dots but cannot draw the one band that is the actual fact. It also means a weekend costs 2,880 entries in a response that exists to carry candles.

The merge rule is CanMerge, deliberately

Adjacent slots coalesce only when status AND reason agree, because CanMerge says so. That is not an optimisation detail, it is the engine’s central claim applied to rendering: a weekend abutting an outage must stay TWO ranges. Merging them files real absence under a closure – unfillable, unalerted, invisible – or files a closure as a recoverable hole and invites someone to fabricate a weekend’s candles. Reusing CanMerge rather than re-testing the two fields here is what keeps that rule in one place.

Extent

Each marker stands for the interval BEGINNING at its timestamp, so a run ending at t spans [first, t+interval) – half-open, matching GapRange everywhere else. A non-positive interval degenerates every range to a point, which is the honest answer when the caller cannot say how wide a slot is; callers that have a StreamID should pass StreamID.Interval().

Points must be in ascending timestamp order, which is the order a query returns them in. Non-gap points break a run: they are data, and data between two holes means two holes.

func NewGapRange(startTs, endTs int64, status GapStatus, reason GapReason) GapRange

NewGapRange creates a new GapRange with the given parameters.

func (g GapRange) AcceptAction() AcceptAction

AcceptAction is the one definition of what may be done about g’s acceptance; ingestion.Dispatcher.AcceptGap refuses anything else.

func (g GapRange) Adjacent(other GapRange) bool

Adjacent checks if this gap range is adjacent to another gap range.

func (g GapRange) CanMerge(other GapRange) bool

CanMerge checks if this gap can be merged with another gap. Gaps can be merged if they have the same status and reason, and are overlapping or adjacent.

func (g GapRange) Contains(ts int64) bool

Contains checks if a timestamp is within the gap range.

func (g GapRange) Fillable() (bool, FillRefusal)

Fillable reports whether a gap may accept manually supplied candles, and why not when it may not.

OFF_TIME IS NEVER FILLABLE, AND THAT IS THE POINT

A gap whose reason is market closure describes hours the exchange was SHUT. There is no data for that period – not missing data, absent data – so anything written into it is fabricated by definition. And it would be fabricated permanently, into the one store built to tell a closure apart from a loss: a weekend that has been “filled” is indistinguishable from a weekend that traded, and the distinction this whole engine exists to make is gone for that range with no way to recover it.

This is a stricter rule than “the operator should know better”, because the operator with a CSV of 168 hourly bars for a week does not know which 40 of them the exchange was open for – the calendar does, and it is right here.

What this does NOT do

It does not refuse ORDINARY INGEST for a closed period. If real candles arrive for hours the calendar calls closed, that is evidence the CALENDAR is wrong – an extended session, a holiday schedule that changed – and the right response is to fix the calendar, not to discard market data because a config file disagrees with the exchange. Refusing a deliberate “fill this hole” operation and refusing data that simply arrives are different decisions, and only the first is fabrication.

Status rules

Only OPEN gaps are fillable. FILLING means someone else already started, and allowing a second fill invites two writers racing over one range. CLOSED means it is already filled; a second fill would be a correction, which is a different operation with its own route. An INCOMPLETE mark is filled while OPEN — writing a whole bar over the incomplete one is how — and refused once ACCEPTED, which is the decision to keep the bar as it is.

func (g GapRange) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler. Format: 8 bytes start_ts + 8 bytes end_ts + 1 byte status + 1 byte reason = 18 bytes.

func (g GapRange) Merge(other GapRange) (GapRange, error)

Merge merges this gap with another gap, returning the merged gap.

func (g GapRange) Overlaps(other GapRange) bool

Overlaps checks if this gap range overlaps with another gap range.

func (g GapRange) Split(ts int64) (left, right GapRange, err error)

Split splits this gap at the given timestamp, returning two gaps.

func (g *GapRange) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler.

func (g GapRange) Validate() error

Validate checks if the gap range is valid.

GapStatus

GapStatus says whether a gap is still actionable.

type GapStatus uint8

GapStatus represents the state of a gap in the timeline.

const (
	// GapStatusOpen indicates a gap that has been detected but not yet addressed.
	GapStatusOpen GapStatus = 0
	// GapStatusFilling indicates a gap that is currently being filled with data.
	GapStatusFilling GapStatus = 1
	// GapStatusClosed indicates a gap that has been successfully filled.
	GapStatusClosed GapStatus = 2
	// GapStatusPermanent indicates a gap that cannot be filled.
	GapStatusPermanent GapStatus = 3
	// GapStatusAccepted resolves an INCOMPLETE mark without changing the bar:
	// an operator saw that a derived bar's source had a hole under it and
	// keeps the bar as it is (Phase 8 §8.1.8). It is a status of INCOMPLETE
	// records only, which GapRange.Validate enforces.
	GapStatusAccepted GapStatus = 4
)
func (s GapStatus) String() string

String returns a string representation of the gap status.

func (s GapStatus) Validate() error

Validate checks if the gap status is valid.

GapReason

GapReason says what caused a gap.

type GapReason uint8

GapReason represents the reason for a gap in the timeline.

const (
	// GapReasonUnknown indicates the reason for the gap is unknown.
	GapReasonUnknown GapReason = 0
	// GapReasonCorruption indicates the gap is due to data corruption.
	GapReasonCorruption GapReason = 1
	// GapReasonNetwork indicates the gap is due to network issues.
	GapReasonNetwork GapReason = 2
	// GapReasonCrash indicates the gap is due to a system crash.
	GapReasonCrash GapReason = 3
	// GapReasonMaintenance indicates the gap is due to scheduled maintenance.
	GapReasonMaintenance GapReason = 4
	// GapReasonRateLimit indicates the gap is due to rate limiting.
	GapReasonRateLimit GapReason = 5
	// GapReasonExchange indicates the gap is due to exchange downtime.
	GapReasonExchange GapReason = 6
	// GapReasonManual indicates the gap was created manually.
	GapReasonManual GapReason = 7
	// GapReasonOffTime indicates the gap is due to expected market closure.
	GapReasonOffTime GapReason = 8
	// GapReasonIncomplete marks a DERIVED bar whose window overlaps a gap in
	// its source (Phase 8 §8.1.8). Unlike every other reason it is filed over
	// slots that HOLD data: the bar is stored and returned, carrying the mark.
	// It is never a closure and never missing time.
	GapReasonIncomplete GapReason = 9
)
func (r GapReason) String() string

String returns a string representation of the gap reason.

func (r GapReason) Validate() error

Validate checks if the gap reason is valid.

FillRefusal

FillRefusal is Fillable’s second return: why a gap will not accept manually supplied candles. The zero value means it will.

type FillRefusal string

FillRefusal explains why a gap will not accept manually supplied candles. The zero value means the gap IS fillable.

const (
	// FillRefusalNone means the gap may be filled.
	FillRefusalNone FillRefusal = ""
	// FillRefusalMarketClosed is the important one. See GapRange.Fillable.
	FillRefusalMarketClosed FillRefusal = "the market was closed for this period, so there is no data to recover"
	// FillRefusalPermanent means the gap was written off as unrecoverable.
	FillRefusalPermanent FillRefusal = "this gap is marked permanent and is not considered recoverable"
	// FillRefusalAlreadyClosed means the gap has already been filled.
	FillRefusalAlreadyClosed FillRefusal = "this gap has already been filled"
	// FillRefusalInProgress means another fill is already underway.
	FillRefusalInProgress FillRefusal = "another fill is already in progress for this gap"
	// FillRefusalAccepted means an incomplete bar was accepted as it is.
	FillRefusalAccepted FillRefusal = "this incomplete bar was accepted as it is"
)

Fill-refusal reasons

const (
	FillRefusalNone          = FillRefusalNone
	FillRefusalMarketClosed  = FillRefusalMarketClosed
	FillRefusalPermanent     = FillRefusalPermanent
	FillRefusalAlreadyClosed = FillRefusalAlreadyClosed
	FillRefusalInProgress    = FillRefusalInProgress
	FillRefusalAccepted      = FillRefusalAccepted
)

Fill-refusal reasons, for a caller that wants to branch on WHY rather than display the message.

FillRefusalMarketClosed is the one that matters. A gap whose reason is market closure describes hours the exchange was SHUT, so there is no data to recover and anything written there is fabricated – permanently, into the one store built to tell a closure apart from a loss. Never derive fillability from a gap’s reason yourself; call GapRange.Fillable, which is the single definition the server enforces with.

ListGapsRequest

ListGapsRequest asks for one page of a stream’s gaps.

type ListGapsRequest struct {
	// StreamID names the stream. Unlike LIST_STREAMS this frame is always
	// scoped to one: gaps are a property of a stream's timeline, and a
	// node-wide gap listing would be a report no operator could act on.
	StreamID StreamID
	// StartTime and EndTime bound the window, in Unix nanoseconds. A gap that
	// OVERLAPS the window is returned whole rather than clipped -- a hole is
	// not two holes because a query cut it in half. The summary durations are
	// clipped; see GapSummary.
	StartTime int64
	EndTime   int64
	// Cursor is the StartTs of the last gap of the previous page, meaningful
	// only when HasCursor is set.
	Cursor    int64
	HasCursor bool
	// Limit caps the page. 0 means DefaultListGapsPage; anything above
	// MaxListGapsPage is refused rather than clamped, for the same reason
	// LIST_STREAMS refuses it: silently returning less is how a client
	// concludes there is no more data.
	Limit uint16
	// OpenOnly returns only gaps still in GapStatusOpen. ExcludeOffTime drops
	// scheduled closures whatever their status.
	OpenOnly       bool
	ExcludeOffTime bool
}

ListGapsRequest asks a node for one page of a stream’s gaps.

func ParseListGapsPayload(payload []byte) (ListGapsRequest, error)

ParseListGapsPayload decodes a LIST_GAPS payload.

ListGapsResponse

ListGapsResponse is one page, plus a summary of the whole window.

type ListGapsResponse struct {
	// Gaps is this page, ordered by StartTs ascending -- gap.idx's own order.
	Gaps []GapRange
	// Summary covers the whole requested range. See GapSummary.
	Summary GapSummary
	// HasMore reports that more gaps follow. A client resumes by sending the
	// last gap's StartTs as the next Cursor.
	HasMore bool
}

ListGapsResponse is one page of a stream’s gaps plus a summary of the window.

func ParseListGapsResponsePayload(payload []byte) (ListGapsResponse, error)

ParseListGapsResponsePayload decodes a LIST_GAPS_RESPONSE payload.

GapSummary

GapSummary describes the requested window rather than the page, so it does not change as a caller pages.

type GapSummary struct {
	// MissingDuration is time GENUINELY absent; OffTimeDuration is scheduled
	// closure. Both in nanoseconds, and both CLIPPED to the requested window.
	//
	// Clipping is what keeps the number meaningful. A gap overlapping the
	// window is reported whole in Gaps, but counting it whole here lets "how
	// much of the last hour is missing?" answer with more than an hour.
	//
	// MissingDuration also excludes CLOSED gaps -- their data was written back,
	// so the time is present and only the record of the hole remains. This
	// matches storage.GapIndex.Statistics; the two are pinned together by
	// TestSummarizeGaps_AgreesWithTheGapIndex. OffTimeDuration has no such
	// exclusion because a closure is never filled in the first place.
	MissingDuration int64
	OffTimeDuration int64
	// Count is every gap in the range. OpenCount, OffTimeCount and
	// FillableCount are subsets and do NOT partition it: a gap can be closed
	// or filling as well.
	//
	// FillableCount comes from GapRange.Fillable rather than from a
	// re-derivation here, so a client that trusts it gets the same answer the
	// server would give a fill request.
	Count         uint32
	OpenCount     uint32
	OffTimeCount  uint32
	FillableCount uint32
}

GapSummary describes the whole requested window, not just the returned page.

It is computed over every gap in the range before the page limit applies, because the question an operator asks – “how much of yesterday is actually missing?” – has an answer that does not depend on where the page happened to end. A summary of the page would change as the caller pages, which is worse than not having one.

func SummarizeGaps(gaps []GapRange, windowStart, windowEnd int64) GapSummary

SummarizeGaps computes the window summary for a set of gaps.

In wire rather than in the server for the same reason SortValue is: a client holding a page may want the same numbers, and two implementations of “how much of this window is missing” is the drift this repo has been bitten by four times. Callers pass the gaps that matched the window AFTER any status or reason filtering and BEFORE the page limit – the summary describes the window, not the page.

Durations are clipped to [windowStart, windowEnd). FillableCount comes from types.GapRange.Fillable, never from a local reading of Status and Reason: a count that disagrees with what a fill request would actually accept is worse than no count.